public class Test13 { public static void main(String[] args) throws Exception { Class aClass = Class.forName("annotate.Student2"); //通过反射获得注解 Annotation[] annotations = aClass.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); } //获得注解的value的值 Table t = (Table) aClass.getAnnotation(Table.class); String value = t.value(); System.out.println(value); //获得类指定的注解 java.lang.reflect.Field f = aClass.getDeclaredField("name"); Field annotation = f.getAnnotation(Field.class); System.out.println(annotation.columnName()); System.out.println(annotation.type()); System.out.println(annotation.length()); } } @Table("db_Student") class Student2{ @Field(columnName = "db_id",type = "int",length = 10) private int id; @Field(columnName = "db_name",type = "varchar",length = 10) private String name; @Field(columnName = "db_age",type = "int",length = 10) private int age; public Student2(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public Student2() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student2{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } } //类名的注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Table{ String value(); } //属性的注解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Field{ String columnName(); String type(); int length(); }
Java反射操作注解
于 2023-11-07 15:49:33 首次发布