首页 > 应用开发 > Java > 好程序员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));
}
...
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69913864/viewspace-2728451/ ,如需转载,请注明出处,否则将追究法律责任。