java - 方法注解继承

标签 java inheritance methods annotations

所以,我的问题如下,我正在使用注释来标记类的方法。

我的主要注解是@Action,我需要一个针对特定方法的更强大的注解,即@SpecificAction

所有用@SpecificAction注解的方法都必须注解为@Action。 我的想法是用 @Action 注释 @SpecificAction

@Action
[other irrelevant annotations]
public @interface SpecificAction{}

@SpecificAction
public void specificMethod(){}

我希望 specificMethod.isAnnotationPresent(Action.class) 为真,但事实并非如此。

我怎样才能使 @Action 注释“继承”?

最佳答案

正如@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); 这将返回一个 Map:{interface foo.ParticularAction=@foo.ParticularAction() , 接口(interface) foo.SpecificAction=@foo.SpecificAction()}

关于java - 方法注解继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45369357/

相关文章:

python - 如何为独立指标和相关指标创建Python类?

c# - 使用鉴别器的 Fluent NHibernate 的多级继承

java - 要创建哪些类方法?

javascript - 在Javascript中扩展继承的原型(prototype)方法

java - 需要 Spring Front Controller 和 Bean 概念的指南

Java错误: The method add(String) is undefined for the type String

java - 我在 android studio 中的位置有问题

java - Android 的开源人脸识别

Scala - 组织单例对象层次结构的正确方法是什么?

java - 为什么访问说明符不能用于在 Java 类的方法内部声明的变量?