Java从JDK1.5开始加入“注解”这一功能,目的是为了对抗以C#为首的一批类Java语言,这里简要介绍一下Java注解的使用以及定义等操作。

1.定义一个注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
package myannotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface A {

public int id() default 0;

public String value() default "default";

}

2.定义一个使用了该注解的类:

1
2
3
4
5
6
7
8
9
10
11
12
package myannotation;

@A
public class C {

@A("age")
public int age;

@A(id = 10, value = "welcome")
public void hello(){}

}

3.通过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
package myannotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {

public static void main(String[] args){

if(C.class.isAnnotationPresent(A.class)){
A a = (A)C.class.getAnnotation(A.class);
System.out.printf("Class: id = %s, value = %s\n", a.id(), a.value());
}

Field[] fields = C.class.getFields();
for (Field field : fields){
if(field.isAnnotationPresent(A.class)){
A a = (A)field.getAnnotation(A.class);
System.out.printf("Field: id = %s, value = %s\n", a.id(), a.value());
}
}

Method[] methods = C.class.getMethods();
for (Method method : methods){
if(method.isAnnotationPresent(A.class)){
A a = (A)method.getAnnotation(A.class);
System.out.printf("Method: id = %s, value = %s\n", a.id(), a.value());
}
}

}

}

上面这个类的运行结果为:

Class: id = 0, value = default
Field: id = 0, value = age
Method: id = 10, value = welcome

结果符合我们在类中对注解所赋予的值。