Java注解与反射原理说明

  Java注解与反射原理说明,首先注解若想发挥更大作用,还需借助反射机制之力。通过反射,可以取得一个方法上声明的注解的全部内容。
  一般有两种需求:
  1、取得方法中全部的注解,通过调用getAnnotations来实现。
  2、判断操作是否是指定注解,通过调用getAnnotation来实现。
  下面从源码角度来说明怎样获取这些注解信息。
  源码导读——取得方法中全部的注解

public class AccessibleObject implements AnnotatedElement {
...
//取得全部Annotation
public Annotation[] getAnnotations() {

return getDeclaredAnnotations();

}
...
}
public final class Method extends Executable {
...
public Annotation[] getDeclaredAnnotations() {

//针对Method类,需要调用父类的getDeclaredAnnotations方法
return super.getDeclaredAnnotations();

}
...
}
//Method的父类Executable的getDeclaredAnnotations实现全部注解信息的获取
public abstract class Executable extends AccessibleObject
implements Member, GenericDeclaration {
...
public Annotation[] getDeclaredAnnotations() {

return AnnotationParser.toArray(declaredAnnotations());

}
...
}

源码导读——判断操作是否是指定注解

public final class Method extends Executable {
...
////取得指定Annotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {

return super.getAnnotation(annotationClass);

}
...
}
public abstract class Executable extends AccessibleObject
implements Member, GenericDeclaration {
...
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {

Objects.requireNonNull(annotationClass);
//获得指定注解类的信息
return annotationClass.cast(declaredAnnotations().get(annotationClass));

}
...
}

评论

暂无评论