Java方法上注解值修改不成功的問題
前提介紹:
java獲取方法有兩種方式:
1、class.getMethods
2、class.getDeclaredMethod
查看JDK注釋,這兩個方法:
getMethods:返回一個數(shù)組,其中包含反映該類對象表示的類或接口的所有公共方法的方法對象,包括由類或接口聲明的方法對象以及從超類和超接口繼承的方法對象。
getDeclaredMethod:返回一個方法對象,該對象反映由該類對象表示的類或接口的指定聲明方法。
那方法上面的注解數(shù)據(jù)是掛在哪的呢?
private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
if (declaredAnnotations == null) {
Executable root = getRoot();
if (root != null) {
declaredAnnotations = root.declaredAnnotations();
} else {
declaredAnnotations = AnnotationParser.parseAnnotations(
getAnnotationBytes(),
sun.misc.SharedSecrets.getJavaLangAccess().
getConstantPool(getDeclaringClass()),
getDeclaringClass());
}
}
return declaredAnnotations;
}
//
private Method root;
//
Executable getRoot() {
return root;
}方法上面的注解數(shù)據(jù)是放在root的declaredAnnotations數(shù)組里面的
正文內容:
getMethods獲取的methods和getDeclaredMethod獲取的methods的root是不同的兩個實例。意味著,方法上面的注解實例存在兩個。
so,如果不確定方法上面的注解使用時是從哪里獲?。╣etMethods or getDeclaredMethod)的,哪你兩個方法上面的注解實例都要反射修改。
上個例子:
@SneakyThrows
public void changeAnnotation() {
Method method_4_getMethods = this.getClass().getMethod("annotation");
Options options_4_getMethods = method_4_getMethods.getAnnotationsByType(Options.class)[0];
System.out.println(String.format("getMethods修改前:%d", options_4_getMethods.timeout()));
changeTimeout(options_4_getMethods, 8888);
System.out.println(String.format("getMethods修改后:%d", options_4_getMethods.timeout()));
Method method_4_getDeclaredMethod = this.getClass().getDeclaredMethod("annotation");
Options options_4_getDeclaredMethod = method_4_getDeclaredMethod.getAnnotationsByType(Options.class)[0];
System.out.println(String.format("getDeclaredMethod修改前:%d", options_4_getDeclaredMethod.timeout()));
changeTimeout(options_4_getDeclaredMethod, 9999);
System.out.println(String.format("getDeclaredMethod修改前:%d", options_4_getDeclaredMethod.timeout()));
}
@SneakyThrows
private void changeTimeout(Options options, int timeout) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(options);
Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
memberValues.setAccessible(true);
Map memberValuesMap = (Map) memberValues.get(invocationHandler);
memberValuesMap.put("timeout", timeout);
}
@Options(timeout = -1)
public void annotation() {
}結果輸出
getMethods修改前:-1
getMethods修改后:8888
getDeclaredMethod修改前:-1
getDeclaredMethod修改前:9999
debug:
1、root是兩個實例
2、注解是兩個實例

到此這篇關于Java方法上注解值修改不成功的文章就介紹到這了,更多相關java方法上注解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
elasticsearch數(shù)據(jù)信息索引操作action?support示例分析
這篇文章主要為大家介紹了elasticsearch數(shù)據(jù)信息索引操作action?support示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04

