如何在默认接口方法中读取实现类?

问题描述

我想创建一个认接口方法,该方法可以使用实现类的带注释的值进行响应。

示例:在下面,我希望所有的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

假设您的@Generated注释是javax version,您将获得NPE,因为它在运行时未保留。

请参见@Retention