[英]How to read the implementation class in default interface method?
I want to create a default interface method that can respond with the annotated value of the implementation class.我想创建一个默认接口方法,它可以响应实现 class 的注释值。
Example: in the following, I want all Child implementations to read their own @Generated
value field:示例:在下面,我希望所有 Child 实现都读取自己的
@Generated
值字段:
public interface Parent {
default String[] find() {
return AnnotationUtils.findAnnotation(this.getClass(), Generated.class).value();
}
}
@Generated(value = {"test"})
public class Child implements Parent {
}
Usage:用法:
System.out.println(new Child().find());
Result: NullPointerException
, because the call tries to find the annotation on the Parent
interface class, not the implementation class.结果:
NullPointerException
,因为调用试图在Parent
接口 class 上查找注释,而不是在实现 class 上查找注释。
It it still possible somehow?它仍然有可能以某种方式吗?
Your question is based on a false premise.你的问题是基于一个错误的前提。
this.getClass()
does not return Parent this.getClass()
不返回父级
Assuming your @Generated
annotation is the javax version , you are getting a NPE because it is not retained at runtime.假设您的
@Generated
注释是javax 版本,您将获得一个 NPE,因为它在运行时没有保留。
See @Retention请参阅@Retention
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.