Java注解與反射原理說明
一 點睛
注解若想發(fā)揮更大作用,還需借助反射機制之力。通過反射,可以取得一個方法上聲明的注解的全部內(nèi)容。
一般有兩種需求:
1 取得方法中全部的注解,通過調(diào)用getAnnotations來實現(xiàn)。
2 判斷操作是否是指定注解,通過調(diào)用getAnnotation來實現(xiàn)。
下面從源碼角度來說明怎樣獲取這些注解信息。
二 源碼導(dǎo)讀——取得方法中全部的注解
public class AccessibleObject implements AnnotatedElement { ... //取得全部Annotation public Annotation[] getAnnotations() { return getDeclaredAnnotations(); } ... } public final class Method extends Executable { ... public Annotation[] getDeclaredAnnotations() { //針對Method類,需要調(diào)用父類的getDeclaredAnnotations方法 return super.getDeclaredAnnotations(); } ... } //Method的父類Executable的getDeclaredAnnotations實現(xiàn)全部注解信息的獲取 public abstract class Executable extends AccessibleObject implements Member, GenericDeclaration { ... public Annotation[] getDeclaredAnnotations() { return AnnotationParser.toArray(declaredAnnotations()); } ... }
三 源碼導(dǎo)讀——判斷操作是否是指定注解
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)); } ... }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
Spring Cloud Gateway 使用JWT工具類做用戶登錄校驗功能
這篇文章主要介紹了Spring Cloud Gateway 使用JWT工具類做用戶登錄校驗的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01Springboot項目使用html5的video標(biāo)簽完成視頻播放功能
這篇文章主要介紹了Springboot項目使用html5的video標(biāo)簽完成視頻播放功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12解決nacos項目啟動報錯:Connection refused: no further&
這篇文章主要介紹了解決nacos項目啟動報錯:Connection refused: no further informa問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04java序列化和serialVersionUID的使用方法實例
這篇文章主要介紹了java序列化和serialVersionUID的使用方法實例的相關(guān)資料,這里說明很詳細(xì)的使用方法讓你徹底學(xué)會,需要的朋友可以參考下2017-08-08idea使用帶provide修飾依賴導(dǎo)致ClassNotFound
程序打包到Linux上運行時,若Linux上也有這些依賴,為了在Linux上運行時避免依賴沖突,可以使用provide修飾,本文主要介紹了idea使用帶provide修飾依賴導(dǎo)致ClassNotFound,下面就來介紹一下解決方法,感興趣的可以了解一下2024-01-01