*/
package org.sonar.api.utils;
-import java.lang.annotation.Annotation;
-
/**
* A utility class for annotations
*
* Searches for a class annotation. All inheritance tree is analysed.
*/
public static <A> A getClassAnnotation(final Object object, final Class<A> annotationClass) {
- Class aClass = (object instanceof Class ? (Class)object : object.getClass());
- while (aClass != null) {
- Annotation annotation = aClass.getAnnotation(annotationClass);
- if (annotation != null) {
- return (A) annotation;
- }
+ Class initialClass = (object instanceof Class ? (Class) object : object.getClass());
+ A result = null;
+ Class aClass=initialClass;
+ while (aClass != null && result == null) {
+ result = (A)aClass.getAnnotation(annotationClass);
aClass = aClass.getSuperclass();
}
- return null;
+
+ if (result==null) {
+ Class[] interfaces = initialClass.getInterfaces();
+ for (Class anInterface : interfaces) {
+ result = (A)anInterface.getAnnotation(annotationClass);
+ if (result!=null) {
+ break;
+ }
+ }
+ }
+ return result;
}
}
*/
package org.sonar.api.utils;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.core.IsNull.nullValue;
-import static org.junit.Assert.assertThat;
import org.junit.Test;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.core.IsNull.nullValue;
+import static org.junit.Assert.assertThat;
+
public class AnnotationUtilsTest {
@Test
assertThat(annotation.value(), is("foo"));
}
+ @Test
+ public void searchClassAnnotationInInterface() {
+ FakeAnnotation annotation = AnnotationUtils.getClassAnnotation(new ImplementedClass(), FakeAnnotation.class);
+ assertThat(annotation.value(), is("foo"));
+ }
+
@Test
public void noClassAnnotation() {
FakeAnnotation annotation = AnnotationUtils.getClassAnnotation("a string", FakeAnnotation.class);
class ChildClass extends SuperClass {
+}
+
+@FakeAnnotation("foo")
+interface AnnotatedInterface {
+}
+
+class ImplementedClass implements AnnotatedInterface {
+
}
\ No newline at end of file