您可以使用基本註釋而不是繼承註釋註釋。這是used in Spring framework。
舉個例子
@Target(value = {ElementType.ANNOTATION_TYPE})
public @interface Vehicle {
}
@Target(value = {ElementType.TYPE})
@Vehicle
public @interface Car {
}
@Car
class Foo {
}
然後,您可以檢查,如果一個類被註解爲使用Spring's AnnotationUtilsVehicle
:
Vehicle vehicleAnnotation = AnnotationUtils.findAnnotation (Foo.class, Vehicle.class);
boolean isAnnotated = vehicleAnnotation != null;
此方法實現:
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
還包含其他方法用於搜索方法和其他註釋元素的註釋。 Spring類還可以搜索橋接方法,代理和其他角落案例,特別是在Spring中遇到的角落案例。
註解繼承似乎是基於註釋創建DSL的必備工具。不支持註釋繼承的這種遺憾。 – Ceki
我同意,看起來很自然。特別是在瞭解Java的繼承之後,你會期望它適用於所有事情。 – javydreamercsw