0%

java | 反射操作注解

反射操作注解。

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
package com.redisc;

import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.List;
import java.util.Map;


// 类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
String value();
}

// 属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TableField {
String columnName();

String type();

int length();
}

@Table("student")
class Student {
@TableField(columnName = "id", type = "int", length = 10)
public int id;
@TableField(columnName = "name", type = "varchar", length = 255)
public String name;
}


public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class c1 = Class.forName("com.redisc.Student");

// 通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}

// 获得注解的值
Table annotation = (Table) c1.getAnnotation(Table.class);
System.out.println(annotation.value());

// 获得类指定的注解
Field f = c1.getDeclaredField("name");
TableField tableField = f.getAnnotation(TableField.class);
System.out.println(tableField.columnName());
System.out.println(tableField.type());

}
}

输出

1
2
3
4
@com.redisc.Table("student")
student
name
varchar
请我喝杯咖啡吧~