如果创建自定义注释,则必须使用此处的
Reflection
API
示例进行处理。您可以参考如何声明注释。
这是Java中的示例注释声明的样子。
import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Test { }Retention并被
Target称为
meta-annotations。
RetentionPolicy.RUNTIME表示您想在运行时保留注释,并且可以在运行时访问它。
ElementType.METHOD表示您只能在方法上声明注释,类似地,您可以为类级别,成员变量级别等配置注释。
每个Reflection类都有获取声明的注释的方法。
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) getAnnotation(Class<T> annotationClass)Returns this element's annotation for the specified type if such an annotation is present, else null.public Annotation[] getDeclaredAnnotations()Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.
你会发现这些方法的介绍
Field,
Method,
Class类。
例如在运行时检索指定类上存在的注释
Annotation[] annos = ob.getClass().getAnnotations();



