java - Method annotation inheritance -
so, problem following, i'm using annotations tag methods of class.
my main annotation @action
, need stronger annotation specific methods @specificaction
.
all methods annotated @specificaction
must annotated @action
. idea have @specificaction
annotated @action
.
@action [other irrelevant annotations] public @interface specificaction{}
with
@specificaction public void specificmethod(){}
i expect specificmethod.isannotationpresent(action.class)
true, isn't.
how make @action
annotation "inherited"?
as @assylias's link says, annotations can't inherited, can use composition, , search recursively target annotation this:
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())); } }
if have:
@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() { // ... } }
you can use this: annotationutil.getannotations(specificmethod, action.class);
, this'll return map: {interface foo.particularaction=@foo.particularaction(), interface foo.specificaction=@foo.specificaction()}
Comments
Post a Comment