反射注解的方式

 1 package 反射与注解;
 2 
 3 import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;
 4 
 5 import java.lang.annotation.*;
 6 import java.lang.reflect.Field;
 7 
 8 public class 反射注解 {
 9     public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
10         Class<?> c1 = Class.forName("反射与注解.Student");
11         Annotation[] declaredAnnotations = c1.getDeclaredAnnotations();
12 
13         //获得类注解
14         for (Annotation declaredAnnotation : declaredAnnotations) {
15             System.out.println(declaredAnnotation);
16         }
17 
18         // 获取value的值
19         dbChris annotation = c1.getAnnotation(dbChris.class);
20         System.out.println(annotation.value());
21 
22 
23         //获取指定列的注解
24         Field age = c1.getDeclaredField("age");
25         columnChris annotation1 = age.getAnnotation(columnChris.class);
26         System.out.println(annotation1.colName());
27         System.out.println(annotation1.type());
28         System.out.println(annotation1.length());
29 
30     }
31 }
32 
33 
34 @dbChris("tStudent")
35 class Student {
36     @columnChris(colName = "dId", type = "int", length = 10)
37     private int id;
38     @columnChris(colName = "dAge", type = "int", length = 10)
39     private int age;
40     @columnChris(colName = "dName", type = "varchar", length = 20)
41     private String name;
42 
43     public int getId() {
44         return id;
45     }
46 
47     public void setId(int id) {
48         this.id = id;
49     }
50 
51     public int getAge() {
52         return age;
53     }
54 
55     public void setAge(int age) {
56         this.age = age;
57     }
58 
59     public String getName() {
60         return name;
61     }
62 
63     public void setName(String name) {
64         this.name = name;
65     }
66 
67     public Student(int id, int age, String name) {
68         this.id = id;
69         this.age = age;
70         this.name = name;
71     }
72 
73     @Override
74     public String toString() {
75         return "Student{" +
76                 "id=" + id +
77                 ", age=" + age +
78                 ", name='" + name + '\'' +
79                 '}';
80     }
81 }
82 
83 
84 @Target(ElementType.TYPE)
85 @Retention(RetentionPolicy.RUNTIME)
86 @interface dbChris {
87     String value();
88 }
89 
90 @Target(ElementType.FIELD)
91 @Retention(RetentionPolicy.RUNTIME)
92 @interface columnChris {
93     String colName();
94 
95     String type();
96 
97     int length() default 10;
98 }

 

 

输出结果

 

posted @ 2022-02-09 15:28  Chris丶Woo  阅读(39)  评论(0编辑  收藏  举报