通过反射获取类注解的value值和属性

通过反射获取注解
以及获取注解的value值
以及注解的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import 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;
}


}