正如@ assylias的鏈接稱,批註不能被繼承,但是你可以使用的成分,和遞歸搜索目標的註釋是這樣的:
public static class AnnotationUtil {
private static <T extends Annotation> boolean containsAnnotation(Class<? extends Annotation> annotation, Class<T> annotationTypeTarget, Set<Class<? extends Annotation>> revised) {
boolean result = !revised.contains(annotation);
if (result && annotationTypeTarget != annotation) {
Set<Class<? extends Annotation>> nextRevised = new HashSet<>(revised);
nextRevised.add(annotation);
result = Arrays.stream(annotation.getAnnotations()).anyMatch(a -> containsAnnotation(a.annotationType(), annotationTypeTarget, nextRevised));
}
return result;
}
public static <T extends Annotation> boolean containsAnnotation(Class<? extends Annotation> annotation, Class<T> annotationTypeTarget) {
return containsAnnotation(annotation, annotationTypeTarget, Collections.emptySet());
}
public static <T extends Annotation> Map<Class<? extends Annotation>, ? extends Annotation> getAnnotations(Method method, Class<T> annotationTypeTarget) {
return Arrays.stream(method.getAnnotations()).filter(a -> containsAnnotation(a.annotationType(), annotationTypeTarget)).collect(Collectors.toMap(a -> a.annotationType(), Function.identity()));
}
}
如果您有:
@Retention(RetentionPolicy.RUNTIME)
@interface Action {
}
@Action
@Retention(RetentionPolicy.RUNTIME)
@interface SpecificAction {
}
@Action
@Retention(RetentionPolicy.RUNTIME)
@interface ParticularAction {
}
public class Foo{
@SpecificAction
@ParticularAction
public void specificMethod() {
// ...
}
}
你可以使用這樣的:AnnotationUtil.getAnnotations(specificMethod, Action.class);
這會返回地圖:{interface [email protected](), interface [email protected]()}
'@Action @SpecificAction公共無效specificMethod(){}' – Michael
相關:https://stackoverflow.com/questions/1624084/why-is-not-possible-to-extend-annotations-in-java – assylias
你可以通過添加一個屬性來解決這個問題,比如'String type()默認的「base」;'或'boolean isSpecific default false;'到你的註解中。 –