以下是完整的代碼 -
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
class A2<T> {
T ob;
A2(T ob) {
this.ob = ob;
}
@Annos(str="T example")
T retob() {
return ob;
}
@Override
public String toString() {
Annotation a = null;
try {
Class<?> c = this.getClass();
Method m = c.getMethod("retob");
a = m.getAnnotation(Annos.class);
}catch(NoSuchMethodException NSMe) {
NSMe.printStackTrace();
}
return a==null?"EMPTY":a.toString();
}
public static void main(String args[]) {
System.out.println(new A2<Integer>(2).toString());
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface Annos {
String str();
}
如果我已經覆寫了該toString()方法,那么a.toString()在 return 陳述句和 main 方法中如何作業?
這是輸出 -
java.lang.NoSuchMethodException: A2.retob()
at java.base/java.lang.Class.getMethod(Class.java:2227)
at A2.toString(A2.java:20)
at A2.main(A2.java:28)
EMPTY
為什么它無法獲取方法retob?
uj5u.com熱心網友回復:
解決方法是改變
Method m = c.getMethod("retob");
至
Method m = c.getDeclaredMethod("retob");
這是必需的,因為您的retob方法不是公開的。
從getMethod 的檔案中:
[類的] 宣告的公共實體和靜態方法由 getDeclaredMethods() 回傳并過濾為僅包含與給定名稱和引數型別匹配的公共方法
這意味著getMethod使用getDeclaredMethod但如果不是則忽略該方法public。使用getDeclaredMethod直接解決了這個問題。
關于您關于 toString 的問題:
return a==null?"EMPTY":a.toString();仍然有效,因為ais null。這"EMPTY"就是回傳的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484437.html
