通过反射获取类注解的value值和属性 发表于 2023-02-22 | 分类于 java | 字数统计: 417 | 阅读时长 ≈ 2通过反射获取注解以及获取注解的value值以及注解的属性123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import java.lang.annotation.*;import java.lang.reflect.Field;public class Test16 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class c1 = Class.forName("com.test.reflection.Student2"); //通过反射获取注解 Annotation[] annotations = c1.getAnnotations(); //获取c1的注解 for (Annotation annotation : annotations) { System.out.println(annotation); //遍历输出 } //通过反射获取类注解的value值 Student2.Tablehe tablehe = (Student2.Tablehe)c1.getAnnotation(Student2.Tablehe.class); System.out.println(tablehe.value()); // 通过反射获取指定的注解,例如获取类属性 Field f = c1.getDeclaredField("id"); //获取“name”属性 Student2.Fieldhe annotation = f.getAnnotation(Student2.Fieldhe.class); //得到注解所属的类 System.out.println(annotation.columnName()); //输出属性注解的value System.out.println(annotation.type()); System.out.println(annotation.length()); }}@Student2.Tablehe("db_student") //数据库表的注解class Student2{ @Fieldhe(columnName = "db_age",type = "int",length = 10) //输入定义的三个值 private int age; @Fieldhe(columnName = "db_name",type = "String",length = 20) private String name; @Fieldhe(columnName = "db_int",type = "int",length = 10) private int id; // 类名的注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Tablehe{ String value(); } // 属性的注解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Fieldhe{ //定义了三个值 String columnName(); String type(); int length(); } // 定义类的无参构造器 public Student2() { } // 定义类的有参构造器 public Student2(int age, String name, int id) { this.age = age; this.name = name; this.id = id; } @Override public java.lang.String toString() { return "Student2{" + "age=" + age + ", name=" + name + ", id=" + id + '}'; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; }}