Puede anotar su anotación con una anotación base en lugar de la herencia. Esto es used in Spring framework.
Para dar un ejemplo
@Target(value = {ElementType.ANNOTATION_TYPE})
public @interface Vehicle {
}
@Target(value = {ElementType.TYPE})
@Vehicle
public @interface Car {
}
@Car
class Foo {
}
A continuación, puede comprobar si una clase se anota con Vehicle
usando Spring's AnnotationUtils:
Vehicle vehicleAnnotation = AnnotationUtils.findAnnotation (Foo.class, Vehicle.class);
boolean isAnnotated = vehicleAnnotation != null;
Este método se implementa como:
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {
return findAnnotation(clazz, annotationType, new HashSet<Annotation>());
}
@SuppressWarnings("unchecked")
private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, Set<Annotation> visited) {
try {
Annotation[] anns = clazz.getDeclaredAnnotations();
for (Annotation ann : anns) {
if (ann.annotationType() == annotationType) {
return (A) ann;
}
}
for (Annotation ann : anns) {
if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) {
A annotation = findAnnotation(ann.annotationType(), annotationType, visited);
if (annotation != null) {
return annotation;
}
}
}
}
catch (Exception ex) {
handleIntrospectionFailure(clazz, ex);
return null;
}
for (Class<?> ifc : clazz.getInterfaces()) {
A annotation = findAnnotation(ifc, annotationType, visited);
if (annotation != null) {
return annotation;
}
}
Class<?> superclass = clazz.getSuperclass();
if (superclass == null || Object.class == superclass) {
return null;
}
return findAnnotation(superclass, annotationType, visited);
}
AnnotationUtils
también contiene métodos adicionales para buscar anotaciones sobre métodos y otros elementos anotados. La clase Spring también es lo suficientemente potente como para buscar a través de métodos en puente, proxies y otros casos de esquina, particularmente los encontrados en Spring.
La herencia de anotaciones parece ser una herramienta imprescindible para crear una DSL basada en anotaciones. Qué pena que la herencia de la anotación no sea compatible. – Ceki
Estoy de acuerdo, parece una cosa natural de hacer. Especialmente después de comprender la herencia en Java, esperas que se aplique a todo. – javydreamercsw