一.

@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());

    }

运行结果:

Java之反射机制七:获取注解

相关文章:

  • 2021-04-23
  • 2022-12-23
  • 2022-12-23
  • 2019-12-20
  • 2021-12-06
  • 2021-05-21
猜你喜欢
  • 2022-12-23
  • 2022-01-03
  • 2021-05-14
  • 2022-02-07
  • 2022-12-23
  • 2021-11-04
  • 2022-12-23
相关资源
相似解决方案