通过反射获取加在类上的注解
java中可以通过反射来操作注解,可以获得加在类上面的注解,进而获得加在类上面的注解 的配置参数的值。
加在类上面的注解 Table_Annotation
的定义:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table_Annotation {
// value字段。用于指定当前注解修饰的类对应 数据库中的哪个表。
String value();
}
实体类:Employee
// 使用注解 Table_Annotation 修饰,value字段指定当前类Employee对应数据库中的表 tb_employee
@Table_Annotation(value = "tb_employee")
class Employee {
private int id;
private int age;
private String name;
}
通过反射,操作加在类Employee上面的注解 Table_Annotation
:
public static void main(String[] args) throws NoSuchFieldException {
// 演示通过反射 获取类上加的注解
// 首先,获得 目标类Employee 对应的Class对象
Class<Employee> employeeClass = Employee.class;
// 其次,通过Class对象获得这个类上的所有注解。当然,此处类上只有一个注解Table_Annotation
Annotation[] annotations = employeeClass.getAnnotations();
System.out.println(Arrays.toString(annotations));
// [@reflect_package.Table_Annotation("tb_employee")]
// 获得注解对应的value的值
// 通过指定注解名的方式获得加在类Employee上面的指定注解
Table_Annotation table_annotation = employeeClass.getAnnotation(Table_Annotation.class);
// 通过 .value()的方式,获得这个注解加在类Employee上时,对应的value
String value = table_annotation.value();
System.out.println(value); // tb_employee
}
可以看到,通过反射的方式,获得了加在类Employee上面的注解。进一步,通过指定注解的方式,可以获得加在类上面的指定注解的value字段。从而可以知道类Employee对应的是数据库中的哪张表。
通过反射获取加在字段上的注解
加在类的字段上面的注解 Field_Annotation
:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field_Annotation {
// 指示注解 Field_Annotation 修饰的属性 对应数据库中的表中的哪个字段
String columnName();
// 指示注解 Field_Annotation 修饰的属性 对应字段的属性
String type();
// 指示注解 Field_Annotation 修饰的属性 对应字段的长度
int length();
}
通过反射,操作 加在类Employee 的具体字段 上面的注解 Field_Annotation
:
public static void main(String[] args) throws NoSuchFieldException {
// 首先,获得目标类Employee 的Class对象
Class<Employee> employeeClass = Employee.class;
// 再通过反射获取指定的字段
Field field = employeeClass.getDeclaredField("id");
// 其次,通过反射获取加在这个字段上面的指定注解 Field_Annotation
Field_Annotation field_annotation = field.getAnnotation(Field_Annotation.class);
System.out.println(field_annotation);
// @reflect_package.Field_Annotation(columnName="id", type="int", length=10)
// 最后:获取加在 类Employee的字段id上面的指定注解 Field_Annotation 的三个参数对应的值
System.out.println(field_annotation.columnName()); // id
System.out.println(field_annotation.type()); // int
System.out.println(field_annotation.length()); // 10
}
可以看到,可以通过 反射获取加在类的指定字段上面的注解,进一步,还可以获得修饰字段的指定注解对应的各个参数属性的值。