Java之反射机制七:获取注解
一.
@Data @Table("t_stu") class Stu{ @Field(columnName = "id",length = 20,type = "bigint") private int id; @Field(columnName = "name",length = 50,type = "varchar") private String name; } @Target({ElementType.TYPE}) @Retention(value = RetentionPolicy.RUNTIME) @interface Table{ String value(); } @Target({ElementType.FIELD}) @Retention(value = RetentionPolicy.RUNTIME) @interface Field{ String columnName(); int length(); String type(); }
二·获取注解的相关信息
@Test public void test() throws NoSuchFieldException { //通过反射获取注解 Class<?> clazz = Stu.class; Table table = clazz.getAnnotation(Table.class); //获取注解的类型 System.out.println(table); //获取注解value值 System.out.println(table.value()); //获取指定的注解的值 java.lang.reflect.Field id = clazz.getDeclaredField("id"); Field field = id.getAnnotation(Field.class); System.out.println(field.columnName()); System.out.println(field.length()); System.out.println(field.type()); }
运行结果: