I have an interface with an annotated method. The annotation is marked with @Inherited
, so I expect an implementor to inherit it. However, it is not the case:
Code:
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Example {
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
TestInterface obj = new TestInterface() {
@Override
public void m() {}
};
printMethodAnnotations(TestInterface.class.getMethod("m"));
printMethodAnnotations(obj.getClass().getMethod("m"));
}
private static void printMethodAnnotations(Method m) {
System.out.println(m + ": " + Arrays.toString(m.getAnnotations()));
}
}
interface TestInterface {
@TestAnnotation
public void m();
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface TestAnnotation {}
The above code prints:
public abstract void annotations.TestInterface.m(): [@annotations.TestAnnotation()]
public void annotations.Example$1.m(): []
So the question is why does not the obj.m()
have @TestAnnotation
despite that it implements a method marked with @TestAnnotation
which is @Inherited
?
The annotation can be overridden in case the child class has the annotation. Because there is no multiple inheritance in Java, annotations on interfaces cannot be inherited.
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.
Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces. The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
Annotations on methods are not inherited by default, so we need to handle this explicitly.
From the javadocs of java.lang.annotation.Inherited
:
Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.
From the @Inherited javadoc:
Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.`
In summary, it doesn't apply to methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With