简体   繁体   English

无法从方法获取@override注释

[英]Can't get @override annotation from method

When I get method from class instance, and want to get @override annotation. 当我从class实例中获取方法并想要获取@override注释时。 but method has not any annotation. 但是方法没有任何注释。 Is it impossible to get @override annotation? 是否无法获取@override注释?

code is below. 代码如下。

package com.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.annotation.Resource;

public class ReflectionTest {

    public static void main(String[] args) throws Exception {
        ChildHoge childHoge = new ChildHoge();
        Method method = childHoge.getClass().getMethod("init");
        for (Annotation s : method.getAnnotations()) {
            System.out.println(s);
        }
        Method method2 = childHoge.getClass().getMethod("a");
        for (Annotation a : method2.getAnnotations()) {
            System.out.println(a); // =>@javax.annotation.Resource(mappedName=, shareable=true, type=class java.lang.Object, authenticationType=CONTAINER, lookup=, description=, name=)

        }
    }

}

class SuperHoge {
    public void init() {

    }
}


class ChildHoge extends SuperHoge {
    @Override
    public void init() {
        super.init();
    }
    @Resource
    public void a() {

    }
}
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

It has RetentionPolicy.SOURCE which are discarded by the compiler, which means it cannot be obtained at runtime. 它具有RetentionPolicy.SOURCE ,编译器会丢弃它,这意味着无法在运行时获取它。 You can see this described in JLS 9.6.4.2 . 您可以在JLS 9.6.4.2中看到此内容

If an annotation a corresponds to a type T, and T has a (meta-)annotation m that corresponds to java.lang.annotation.Retention , then: 如果注释a对应于类型T,并且T具有对应于java.lang.annotation.Retention的(元)注释m,则:

  • If m has an element whose value is java.lang.annotation.RetentionPolicy.SOURCE , then a Java compiler must ensure that a is not present in the binary representation of the class or interface in which a appears. 如果m具有一个值为java.lang.annotation.RetentionPolicy.SOURCE的元素,则Java编译器必须确保a出现在类或接口的二进制表示形式中不存在a。

And the Javadoc for RetentionPolicy also describes this: 而且RetentionPolicy的Javadoc也对此进行了描述:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,
    ...

You can use Reflection API to check if the method is overridden or not eg 您可以使用Reflection API来检查该方法是否被覆盖,例如

class.getMethod("myMethod").getDeclaringClass();

If the class that's returned is your own, then it's not overridden; 如果返回的类是您自己的,则不会被覆盖; if it's something else, that subclass has overridden it. 如果还有其他内容,则该子类已覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM