Last active
June 9, 2017 11:03
-
-
Save mbjelac/40316fac5e70cc8eb836b91f0d734cc5 to your computer and use it in GitHub Desktop.
a JUnit test demonstrating how Java treats annotations of inherited methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import java.lang.annotation.Annotation; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.reflect.Method; | |
import static org.junit.Assert.assertFalse; | |
import static org.junit.Assert.assertTrue; | |
public class AnnotationInheritanceTest { | |
@Retention(RetentionPolicy.RUNTIME) | |
@interface Interesting { } | |
class Parent { | |
@Interesting | |
public void method1() { } | |
@Interesting | |
public void method2() { } | |
} | |
class Child extends Parent { | |
public void method2() { } | |
} | |
@Test | |
public void methodAnnotationIsInheritedWhenMethodNotOverridden() | |
throws NoSuchMethodException { | |
assertTrue(methodHasAnnotation( | |
Child.class.getMethod("method1"), | |
Interesting.class)); | |
assertFalse(methodHasAnnotation( | |
Child.class.getMethod("method2"), | |
Interesting.class)); | |
} | |
private boolean methodHasAnnotation( | |
Method method, | |
Class<? extends Annotation> annotationType | |
) { | |
return method.getDeclaredAnnotation(annotationType) != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment