![](/img/trans.png)
[英]How to invoke an interface's default implementation of a method in an overriding implementation?
[英]How to read the implementation class in default interface method?
我想創建一個默認接口方法,它可以響應實現 class 的注釋值。
示例:在下面,我希望所有 Child 實現都讀取自己的@Generated
值字段:
public interface Parent {
default String[] find() {
return AnnotationUtils.findAnnotation(this.getClass(), Generated.class).value();
}
}
@Generated(value = {"test"})
public class Child implements Parent {
}
用法:
System.out.println(new Child().find());
結果: NullPointerException
,因為調用試圖在Parent
接口 class 上查找注釋,而不是在實現 class 上查找注釋。
它仍然有可能以某種方式嗎?
你的問題是基於一個錯誤的前提。 this.getClass()
不返回父級
假設您的@Generated
注釋是javax 版本,您將獲得一個 NPE,因為它在運行時沒有保留。
請參閱@Retention
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.