Java注解與反射原理說明
一 點(diǎn)睛
注解若想發(fā)揮更大作用,還需借助反射機(jī)制之力。通過反射,可以取得一個方法上聲明的注解的全部內(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)文章
Java Eclipse進(jìn)行斷點(diǎn)調(diào)試的方法
本篇文章主要介紹了Java Eclipse進(jìn)行斷點(diǎn)調(diào)試的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
Java解決浮點(diǎn)數(shù)計算不精確問題的方法詳解
在 Java 中,浮點(diǎn)數(shù)計算不精確問題指的是使用浮點(diǎn)數(shù)進(jìn)行運(yùn)算時,由于浮點(diǎn)數(shù)的內(nèi)部表示方式和十進(jìn)制數(shù)的表示方式存在差異,導(dǎo)致計算結(jié)果可能出現(xiàn)誤差,本文就給大家介紹一下Java如何解決浮點(diǎn)數(shù)計算不精確問題,需要的朋友可以參考下2023-09-09
Java報錯:FileNotFoundException的解決方案
在Java編程中,FileNotFoundException 是一種常見的受檢異常,通常發(fā)生在試圖打開一個不存在的文件或文件路徑錯誤時,本文將詳細(xì)探討FileNotFoundException的成因、解決方案以及預(yù)防措施,幫助開發(fā)者理解和避免此類問題,需要的朋友可以參考下2024-06-06
解決Spring Cloud Gateway獲取body內(nèi)容,不影響GET請求的操作
這篇文章主要介紹了解決Spring Cloud Gateway獲取body內(nèi)容,不影響GET請求的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12
BeanUtils.copyProperties復(fù)制屬性失敗的原因及解決方案
這篇文章主要介紹了BeanUtils.copyProperties復(fù)制屬性失敗的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

