Java 方法注释如何与方法覆盖结合使用? [英] How do Java method annotations work in conjunction with method overriding?

查看:31
本文介绍了Java 方法注释如何与方法覆盖结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类 Parent 和一个子类 Child,定义如下:

class Parent {@MyAnnotation(你好")无效的 foo() {//实现无关}}类子扩展父{@覆盖富(){//实现无关}}

如果我获得了对 Child::fooMethod 引用,childFoo.getAnnotation(MyAnnotation.class) 会给我 @MyAnnotation?或者它会是 null?

我对注解如何或是否与 Java 继承一起工作更感兴趣.

解决方案

http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance:

<块引用>

注解继承

了解与注解继承相关的规则很重要,因为这些规则会影响基于注解存在与否的连接点匹配.

默认情况下注解不会被继承.鉴于以下程序

 @MyAnnotation类超级{@Oneway 公共无效 foo() {}}类子扩展超级{公共无效 foo() {}}

<块引用>

然后 Sub 没有 MyAnnotation 注释,并且 Sub.foo() 不是 @Oneway> 方法,尽管它覆盖了 Super.foo() .

如果注解类型具有元注解@Inherited,那么类上该类型的注解将导致子类继承该注解.因此,在上面的示例中,如果 MyAnnotation 类型具有 @Inherited 属性,则 Sub 将具有 MyAnnotation> 注释.

@Inherited 注释在用于注释类型以外的任何内容时不会被继承.实现一个或多个接口的类型永远不会从它实现的接口继承任何注解.

I have a parent class Parent and a child class Child, defined thus:

class Parent {
    @MyAnnotation("hello")
    void foo() {
        // implementation irrelevant
    }
}
class Child extends Parent {
    @Override
    foo() {
        // implementation irrelevant
    }
}

If I obtain a Method reference to Child::foo, will childFoo.getAnnotation(MyAnnotation.class) give me @MyAnnotation? Or will it be null?

I'm interested more generally in how or whether annotation works with Java inheritance.

解决方案

Copied verbatim from http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance:

Annotation Inheritance

It is important to understand the rules relating to inheritance of annotations, as these have a bearing on join point matching based on the presence or absence of annotations.

By default annotations are not inherited. Given the following program

        @MyAnnotation
        class Super {
          @Oneway public void foo() {}
        }

        class Sub extends Super {
          public void foo() {}
        }

Then Sub does not have the MyAnnotation annotation, and Sub.foo() is not an @Oneway method, despite the fact that it overrides Super.foo() which is.

If an annotation type has the meta-annotation @Inherited then an annotation of that type on a class will cause the annotation to be inherited by sub-classes. So, in the example above, if the MyAnnotation type had the @Inherited attribute, then Sub would have the MyAnnotation annotation.

@Inherited annotations are not inherited when used to annotate anything other than a type. A type that implements one or more interfaces never inherits any annotations from the interfaces it implements.

这篇关于Java 方法注释如何与方法覆盖结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆