无法从方法获取@override注释



当我从 class实例中获得方法时,想要获得 @override注释。但是方法没有任何注释。是否无法获得@override注释?

代码在下面。

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 {
}

它具有由编译器丢弃的RetentionPolicy.SOURCE,这意味着它在运行时无法获得。您可以在JLS 9.6.4.2。

中看到此描述。

如果注释A对应于T型,并且T具有 (元)注释m java.lang.annotation.Retention,然后:

  • 如果m具有其价值的元素 java.lang.annotation.RetentionPolicy.SOURCE,然后是Java编译器必须 确保班级的二进制表示中不存在a 或出现的接口。

RetentionPolicy的Javadoc也描述了这一点:

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

您可以使用反射API检查该方法是否被覆盖例如

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

如果返回的班级是您自己的班级,则不会被覆盖;如果是其他的,那子类已覆盖它。

最新更新