Actually, I don't get how this is even remotely tricky.
Update, forgot to include the contains function and also made a mistake switching Annotation.getClass() with Annotation.annotationType(). This code works
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Mark
public @interface A {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface B {}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Mark {}
public class C {
@A @B public void f() {}
}
public class Solver {
public static boolean contains(Annotation a, Class<?> targetAnnotation) {
Class<?> c = a.annotationType();
Annotation[] cas = c.getAnnotations();
for (Annotation aa : cas) {
if (aa.annotationType().equals(targetAnnotation)) {
return true;
}
}
return false;
}
public static Annotation[] getMarked(Method m) {
List<Annotation> retVal = new ArrayList<Annotation>();
for (Annotation a : m.getAnnotations()) {
if (contains(a.getClass().getAnnotations(), Mark.class) {
retVal.add(a);
}
}
return retVal.toArray(new Annotation[]{});
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
Annotation[] result = getMarked(C.class.getMethod("f"));
}
} // solver
Note that this requires that all the annotations be marked with runtime level retention and also that returning Annotation[] is probably not what you want. You probably want to return a Class[] full of the actual types (in my example, A.class)