一 點睛
注解若想發揮更大作用,還需借助反射機制之力。通過反射,可以取得一個方法上聲明的注解的全部內容。
一般有兩種需求:
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)); } ...}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選