【问题标题】:How to read the implementation class in default interface method?如何读取默认接口方法中的实现类?
【发布时间】: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接口类上的注解,而不是实现类。

它仍然有可能吗?

【问题讨论】:

标签: java spring reflection annotations


【解决方案1】:

您的问题基于错误的前提。 this.getClass() does not return Parent

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

@Retention

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 2015-07-31
    • 1970-01-01
    • 2014-12-03
    • 2018-10-15
    • 2021-11-21
    • 2016-06-16
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多