Why java classes do not inherit annotations from implemented interfaces?

Boris Pavlović picture Boris Pavlović · Jan 20, 2011 · Viewed 62.6k times · Source

I've been using Guice's AOP to intercept some method calls. My class implements an interface and I would like to annotate the interface methods so Guice could select the right methods. Even if the annotation type is annotated with Inherited annotation implementing class doesn't inherit the annotation as stated in Inherited's java doc:

Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

What could be the reason for this? Getting to know all interfaces that an object's class does implement in runtime is not that hard thing to do so there must be a good reason behind this decision.

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Jan 20, 2011

I'd say the reason is that otherwise a multiple-inheritance problem would occur.

Example:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Inherited
public @interface Baz { String value(); }

public interface Foo{
    @Baz("baz") void doStuff();
}

public interface Bar{
    @Baz("phleem") void doStuff();
}

public class Flipp{
    @Baz("flopp") public void doStuff(){}
}

public class MyClass extends Flipp implements Foo, Bar{}

If I do this:

MyClass.class.getMethod("doStuff").getAnnotation(Baz.class).value()

what's the result going to be? 'baz', 'phleem' or 'flopp'?


For this reason, annotations on interfaces are rarely useful.