Java動態(tài)設置注解值及原理詳解
更新時間:2023年11月27日 09:58:43 作者:一碼評川
這篇文章主要介紹了Java動態(tài)設置注解值及原理詳解,AnnotationInvocationHandler是注解的代理hander,通過反射獲取類的注解時會通過AnnotationInvocationHandler創(chuàng)建代理對象并將數(shù)據(jù)存儲到memberValues里,需要的朋友可以參考下
Java動態(tài)注解值原理
描述:在運行時根據(jù)需求更改注解中的值
一、步驟
1.定義類
public class CadreListQueryDTO extends CadreBaseQueryDTO {
/**
* 出國事由
*/
@QueryField(field = "A21.a2114",type = QueryField.LIKE)
private String a2114;
}
2.定義方法進行動態(tài)設置
/**
* 動態(tài)設置注解值
*
* @param annotation
* @param valueName
* @param value
* @param <T>
*/
@SneakyThrows
public static <T extends Annotation> void setValueToAnnotate(T annotation, String valueName, Object value) {
InvocationHandler invocationHandler = null;
if (Objects.nonNull(annotation)) {
invocationHandler = Proxy.getInvocationHandler(annotation);
}
if (Objects.isNull(invocationHandler)) {
return;
}
Field nameField = invocationHandler.getClass().getDeclaredField("memberValues");
nameField.setAccessible(true);
Map<String, Object> memberValues = (Map<String, Object>) nameField.get(invocationHandler);
memberValues.put(valueName, value);
}
3.測試
public static void main(String[] args) {
try {
QueryField queryField = CadreListQueryDTO.class.getDeclaredField("a2114").getAnnotation(QueryField.class);
System.out.println("修改前:"+ queryField.field());
setValueToAnnotate(queryField,"field","哈哈哈哈");
System.out.println("修改前:"+ queryField.field());
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}

二、原理分析
- AnnotationInvocationHandler是注解的代理hander
- 通過反射獲取類的注解時會通過AnnotationInvocationHandler創(chuàng)建代理對象并將數(shù)據(jù)存儲到memberValues里

修改memberValues里的數(shù)據(jù)

獲取結果

到此這篇關于Java動態(tài)設置注解值及原理詳解的文章就介紹到這了,更多相關Java動態(tài)注解值原理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
windows系統(tǒng)配置Java開發(fā)環(huán)境變量
這篇文章主要介紹了windows系統(tǒng)配置Java開發(fā)環(huán)境變量,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-12-12
SpringBoot分布式文件存儲數(shù)據(jù)庫mongod
MongoDB是一個基于分布式文件存儲的NoSQL數(shù)據(jù)庫,由C++語言編寫,旨在為Web應用提供可擴展的高性能數(shù)據(jù)存儲解決方案。MongoDB是一個介于關系數(shù)據(jù)庫和非關系數(shù)據(jù)庫之間的產(chǎn)品,是非關系數(shù)據(jù)庫中功能最豐富最像關系數(shù)據(jù)庫的2023-02-02

