无法从方法中获取@override 注释

Can't get @override annotation from method

当我从 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.

中看到这个描述

If an annotation a corresponds to a type T, and T has a (meta-)annotation m that corresponds to java.lang.annotation.Retention, then:

  • 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.

RetentionPolicy 的 Javadoc 也描述了这一点:

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

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

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

如果返回的 class 是您自己的,则不会被覆盖;如果是其他情况,则 subclass 已覆盖它。