Java Annotation注释语法参考
??????????????? MyAnnotation3 fieldAnnotation = field.getAnnotation(MyAnnotation3.class );?
??????????????? printMyAnnotation3(fieldAnnotation);?
??????????? }?
??????? }?
????????
??????? System.out.println("--Methods Annotations-- ");?
??????? Method[] methods = GetMyAnnotation.class.getDeclaredMethods();?
??????? for (Method method : methods) {?
??????????? System.out.println("[GetMyAnnotation. " + method.getName() + "].annotation: ");?
??????????? if (method.isAnnotationPresent(MyAnnotation3.class )) {?
??????????????? MyAnnotation3 methodAnnotation = method.getAnnotation(MyAnnotation3.class );?
??????????????? printMyAnnotation3(methodAnnotation);??
??????????? }?
??????? }?
??? }?
????
??? private static void printMyAnnotation3(MyAnnotation3 annotation3) {?
??????? if (annotation3 == null ) {?
??????????? return;?
??????? }?
????????
??????? System.out.println("{value= " + annotation3.value());?
????????
??????? String multiValues = "";?
??????? for (String value: annotation3.multiValues()) {?
??????????? multiValues += ", " + value;?
??????? }?
????????
??????? System.out.println("multiValues= " + multiValues);?
????????
??????? System.out.println("number= " + annotation3.number() + "} ");?
??? }?
}?
输出:?
--Class Annotations--?
[GetMyAnnotation].annotation:?
{value=Class GetMyAnnotation?
multiValues=,1,2?
number=0}?
--Fields Annotations--?
[GetMyAnnotation.testField1].annotation:?
{value=call testField1?
multiValues=,1?
number=1}?
--Methods Annotations--?
[GetMyAnnotation.testMethod1].annotation:?
{value=call testMethod1?
multiValues=,1,2?
number=1}?
[GetMyAnnotation.testMethod2].annotation:?
{value=call testMethod2?
multiValues=,3,4,5?
number=0}?
JDK1.5以后的版本提供的跟annotation有关的接口:?
interface java.lang.reflect.AnnotatedElement {?
??? boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);?
??? <T extends Annotation> T getAnnotation(Class<T> annotationClass);?
??? Annotation[] getAnnotations();?
??? Annotation[] getDeclaredAnnotations();?
}?
该接口主要用来取得附加在类(class),构造方法(constructor),属性(field),方法(method),包(package)上的annotation信息。?
JDK1.5与此有关的几个类都实现了AnnotatedElement接口:?
java.lang.reflect.AccessibleObject,?
java.lang.reflect.Class,?
java.lang.reflect.Constructor,?
java.lang.reflect.Field,?
java.lang.reflect.Method,?
java.lang.reflect.Package?
所以可以利用反射(reflection)功能在程序里动态解析附加的annotation信息。?
总结:?
本文通过举例简单地说明了怎么动态解析annotation,大家可以举一反三,利用Java的annotation特性,完成更复杂功能等。????