<强>一,点睛强>
注解若想发挥更大作用,还需借助反射机制之力。通过反射,可以取得一个方法上声明的注解的全部内容。
一般有两种需求:
1,取得方法中全部的注解,通过调用getAnnotations来实现。
2,判断操作是否是指定注解,通过调用getAnnotation来实现。
下面从源码角度来说明怎样获取这些注解信息。
<强>二源码导读——取得方法中全部的注解强>
公共类AccessibleObject实现AnnotatedElement { …//取得全部注释 公共注释[]getAnnotations () { 返回getDeclaredAnnotations (); } … } 最后公共类方法扩展了可执行{ … 公共注释[]getDeclaredAnnotations () {//针对类方法,需要调用父类的getDeclaredAnnotations方法 返回super.getDeclaredAnnotations (); } … }//方法的父类可执行的getDeclaredAnnotations实现全部注解信息的获取 公共抽象类可执行AccessibleObject延伸 实现成员,GenericDeclaration { … 公共注释[]getDeclaredAnnotations () { 返回AnnotationParser.toArray (declaredAnnotations ()); } … }
<强>三源码导读——判断操作是否是指定注解强>
最后公共类方法扩展了可执行{ …////取得指定注释 公共& lt; T Annotation>延伸;T getAnnotation (ClassannotationClass) { 返回super.getAnnotation (annotationClass); } … } 公共抽象类可执行AccessibleObject延伸 实现成员,GenericDeclaration { … 公共& lt; T Annotation>延伸;T getAnnotation (Class annotationClass) { Objects.requireNonNull (annotationClass);//获得指定注解类的信息 返回annotationClass.cast (declaredAnnotations () . get (annotationClass)); } … }
<强>总结强>
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接