Java从JDK1.5开始加入“注解”这一功能,目的是为了对抗以C#为首的一批类Java语言,这里简要介绍一下Java注解的使用以及定义等操作。
1.定义一个注解:
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.定义一个使用了该注解的类:
package myannotation;
@A
public class C {
@A("age")
public int age;
@A(id = 10, value = "welcome")
public void hello(){}
}
3.通过Java的反射机制来实现「注解处理器」:
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
结果符合我们在类中对注解所赋予的值。
太晚了,先写到这里,有时间再写。