如果您创建自定义注释,则必须使用Reflection
API Example Here来处理它们。您可以参考如何声明注释。
这是 java 中的示例注释声明的样子。
import java.lang.annotation.*;
/**
* Indicates that the annotated method is a test method.
* This annotation should be used only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
Retention
并且Target
被称为meta-annotations
。
RetentionPolicy.RUNTIME
表示要在运行时保留注解,并且可以在运行时访问它。
ElementType.METHOD
表示您只能在方法上声明注释,类似地您可以为类级别、成员变量级别等配置注释。
每个反射类都有方法来获取声明的注解。
public <T extends Annotation> T 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();