Android AOP之注解处理解释器详解(二)之注解处理解释器详解(二)
Android APO 注解处理解释器注解处理解释器
相关文章:相关文章:
Android AOP注解注解Annotation详解(一)详解(一)
Android AOP之注解处理解释器详解(二)之注解处理解释器详解(二)
Android AOP 注解详解及简单使用实例(三)注解详解及简单使用实例(三)
一、提取一、提取Annotation信息信息
当开发者使用了Annotation修饰了类、方法、Field等成员之后,这些Annotation不会自己生效,必须由开发者提供相应的代码
来提取并处理Annotation信息。这些处理提取和处理Annotation的代码统称为APT(Annotation Processing Tool)。
JDK主要提供了两个类,来完成Annotation的提取:
Java.lang.annotation.Annotation接口:这个接口是所有Annotation类型的父接口。
java.lang.reflect.AnnotatedElement接口:该接口代表程序中可以被注解的程序元素。
1.1 Annotation接口
这个接口比较少用,这个接口里面有四个方法:
package java.lang.annotation;
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
//返回该注解的Class,元素使用了多个注解的时候,可以进行输出判断
Class<? extends Annotation> annotationType();
}
1.2 AnnotatedElement接口
该接口最常用的方法是isAnnotationPresent()、getAnnotation(Class annotationClass):
package java.lang.reflect;
import java.lang.annotation.Annotation;
public interface AnnotatedElement {
//判断此元素上是否存在指定类型的注解,如果存在则返回true,否则返回false
default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return getAnnotation(annotationClass) != null;
}
//返回此元素上存在的指定类型的注解,如果该类型的注解不存在,则返回null
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
//返回此元素上存在的所有注解。
Annotation[] getAnnotations();
//返回此元素上存在的所有注解。不包括继承
Annotation[] getDeclaredAnnotations();
default <T extends Annotation> Annotation getDeclaredAnnotation(Class<T> annotationClass) {
return AnnotatedElements.getDeclaredAnnotation(this, annotationClass);
}
default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
return AnnotatedElements.getDeclaredAnnotationsByType(this, annotationClass);
}