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