【发布时间】:2020-08-12 13:29:27
【问题描述】:
我想创建一个默认的接口方法,可以用实现类的注解值来响应。
示例:在下面,我希望所有 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接口类上的注解,而不是实现类。
它仍然有可能吗?
【问题讨论】:
-
您的问题是基于错误的前提。
this.getClass()does not return Parent
标签: java spring reflection annotations