简体   繁体   中英

Can't get @override annotation from method

When I get method from class instance, and want to get @override annotation. but method has not any annotation. Is it impossible to get @override annotation?

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. You can see this described in 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.

And the Javadoc for RetentionPolicy also describes this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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