Inheriting annotations from implemented interfaces

In relation to Rick Hightower entry on annotations and inheritance I also checked if annotations on implemented interfaces are accesible
from the class implementing them. The answer is NO, neither using the
@Inherited annotation on the annotation class. The only way is getting
the implemented interfaces and iterate over them to see if they have
annotations.

public class AnnotationTest extends TestCase {

    @Retention(RetentionPolicy.RUNTIME) // This makes the annotation available at runtime
    @Inherited
    public static @interface Developer {
        String name();

        String email() default “somebody@somewhere.com”;

        int rank() default 1;
    }

    // Using the annotation to decorate a class and a method
    @Developer(name = “RickHightower”)
    interface MyInterface {
        @Developer(name = “ScottFauerbach”, email = “foobar@foo.com”)
        void myMethod();
    }

    class MyClassSub implements MyInterface {
        
        public void myMethod() {
            // …
        }
    }

    // Testing the annotation
    public void testAnnotation() throws Exception {
        assertFalse (MyClassSub.class.isAnnotationPresent(Developer.class));
        Method method2 = MyClassSub.class.getMethod(“myMethod”, (Class[]) null);
        assertFalse (method2.isAnnotationPresent(Developer.class));
        
        Class[] interfaces = MyClassSub.class.getInterfaces();
        boolean annotationPresent = false;
        for (Class iClass : interfaces) {
            if (iClass.isAnnotationPresent(Developer.class)) {
                   
annotationPresent = true;
                    break;
            }
        }
        assertTrue(annotationPresent);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s