【问题标题】:How to use @inherited annotation in Java?如何在 Java 中使用 @inherited 注解?
【发布时间】:2014-07-21 07:20:54
【问题描述】:

我没有在 Java 中获得 @Inherited 注释。如果它自动为您继承方法,那么如果我需要以自己的方式实现该方法,那又如何呢?

它将如何知道我的实现方式?

另外据说如果我不想使用它并以老式的 Java 方式执行它,我必须实现 equals()toString()hashCode()Object 方法类,也是java.lang.annotation.Annotation类的注解类型方法。

这是为什么呢?

即使我不知道 @Inherited 注释和过去也可以正常工作的程序,我也从未实现过这些。

请有人从头开始解释一下。

【问题讨论】:

    标签: java inheritance annotations


    【解决方案1】:

    只是没有误解:您确实询问了java.lang.annotation.Inherited。这是注解的注解。表示被注解的类的子类被认为与它们的超类具有相同的注解。

    示例

    考虑以下 2 个注释:

    @Inherited
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface InheritedAnnotationType {
        
    }
    

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface UninheritedAnnotationType {
        
    }
    

    如果三个类是这样注释的:

    @UninheritedAnnotationType
    class A {
        
    }
    
    @InheritedAnnotationType
    class B extends A {
        
    }
    
    class C extends B {
        
    }
    

    运行此代码

    System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class));
    System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class));
    System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class));
    System.out.println("_________________________________");
    System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class));
    System.out.println(new B().getClass().getAnnotation(UninheritedAnnotationType.class));
    System.out.println(new C().getClass().getAnnotation(UninheritedAnnotationType.class));
    

    会打印出类似这样的结果(取决于注解的包):

    null
    @InheritedAnnotationType()
    @InheritedAnnotationType()
    _________________________________
    @UninheritedAnnotationType()
    null
    null
    

    如您所见,UninheritedAnnotationType 没有被继承,但CB 继承注释InheritedAnnotationType

    我不知道这与什么方法有关。

    【讨论】:

    • 这对类很有用,但如果这些是接口,为什么不呢?只需将 A、B、C 类作为接口并使用 C.class.getAnnotation(InheritedAnnotationType.class) 并不起作用?
    • @saurabh 实际上这不适用于接口,请参阅 javadoc docs.oracle.com/javase/8/docs/api/java/lang/annotation/… : "如果注释类型声明中存在继承的元注释,并且用户查询注释类型在类声明上,并且类声明没有该类型的注释,则将自动查询该类的超类的注释类型。”(如果您也考虑接口,则类的层次结构是“一行” ,它可能会变成“一棵树”,导致查找效率低下和/或冲突。)
    • 我们也可以用A.class.isAnnotationPresent(InheritedAnnotationType.class)简化测试,它会返回一个布尔值。
    • @saurabh 我知道这个旧的,但因为它仍然相关,文档状态:“请注意,如果注释类型用于注释除类。另请注意,此元注释仅导致注释从超类继承;已实现接口上的注释无效。"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多