Inheriting method annotations

So my problem is this: I use annotations for class method tags.

My main annotation @Action, and I need a stronger annotation for certain methods that are @SpecificAction.

All methods annotated with help @SpecificActionshould be annotated as @Action. My idea is to @SpecificActionbe annotated with help @Action.

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

with

@SpecificAction
public void specificMethod(){}

I would expect it to specificMethod.isAnnotationPresent(Action.class)be true, but it is not.

How can I make the annotation @Action“inherited”?

+4
source share
1 answer

@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 foo.ParticularAction=@foo.ParticularAction(), interface foo.SpecificAction=@foo.SpecificAction()}

+3

Source: https://habr.com/ru/post/1682475/


All Articles