Java注解与反射原理说明
一 点睛
注解若想发挥更大作用,还需借助反射机制之力。通过反射,可以取得一个方法上声明的注解的全部内容。
一般有两种需求:
1 取得方法中全部的注解,通过调用getAnnotations来实现。
2 判断操作是否是指定注解,通过调用getAnnotation来实现。
下面从源码角度来说明怎样获取这些注解信息。
二源码导读——取得方法中全部的注解
publicclassAccessibleObjectimplementsAnnotatedElement{
...
//取得全部Annotation
publicAnnotation[]getAnnotations(){
returngetDeclaredAnnotations();
}
...
}
publicfinalclassMethodextendsExecutable{
...
publicAnnotation[]getDeclaredAnnotations(){
//针对Method类,需要调用父类的getDeclaredAnnotations方法
returnsuper.getDeclaredAnnotations();
}
...
}
//Method的父类Executable的getDeclaredAnnotations实现全部注解信息的获取
publicabstractclassExecutableextendsAccessibleObject
implementsMember,GenericDeclaration{
...
publicAnnotation[]getDeclaredAnnotations(){
returnAnnotationParser.toArray(declaredAnnotations());
}
...
}
三源码导读——判断操作是否是指定注解
publicfinalclassMethodextendsExecutable{
...
////取得指定Annotation
publicTgetAnnotation(ClassannotationClass){
returnsuper.getAnnotation(annotationClass);
}
...
}
publicabstractclassExecutableextendsAccessibleObject
implementsMember,GenericDeclaration{
...
publicTgetAnnotation(ClassannotationClass){
Objects.requireNonNull(annotationClass);
//获得指定注解类的信息
returnannotationClass.cast(declaredAnnotations().get(annotationClass));
}
...
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接