自定义注解

2019-11-01  本文已影响0人  IT_lz

jdk1.5之后新增了注解功能,用于简化代码。
例如:

    // (过期注解)
    @Deprecated 
    public void delate() {
    }

    // (重写注解)
    @Override
    public String toString() {
        return super.toString();
    }

    public void add() {
        // 被过期修的的方法,会被打上横线
        delate();
    }

一、注解事例分析

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

上面是Override注解的源码

二、实例演示

@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
@interface TestAnnotation{
  int beanId() default 0;
  String name() default "";
  String[] arr();
}


public class Test001 {
  @TestAnnotation(beanId = 10, arr = {"lz", "haha"})
  public void add() {
      
  }
}

三、自定义注解实现ORM框架映射

1、定义注解Table类
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
    String value() default "";
}
2、定义注解Property类
@Retention(RetentionPolicy.RUNTIME)
@interface Property {
    String name();
}
3、定义实体类并注解
@Table("table_student")
class Student{

    @Property(name = "stu_id")
    private String stuId;

    @Property(name = "stu_name")
    private String stuName;

    @Property(name = "stu_age")
    private String stuAge;
}
4、测试类
       Class<?> aClass = Class.forName("com.liu.annotation.Student");
        //获取类注解
        Table table = aClass.getDeclaredAnnotation(Table.class);
        
        // 获取属性集合
        Field[] declaredFields = aClass.getDeclaredFields();

        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append("select ");

        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            // 获取每个属性的注解
            Property annotation = field.getDeclaredAnnotation(Property.class);
            if (i < declaredFields.length) {
                stringBuffer.append(annotation.name()+ ", ");
            }
        }
        stringBuffer.append("from "+table.value());
        System.out.println(stringBuffer.toString());

打印结果
select stu_id, stu_name, stu_age, from table_student

上一篇 下一篇

猜你喜欢

热点阅读