实际上,我不明白这有多么棘手。
更新,忘记包含 contains 函数,并且在将 Annotation.getClass() 与 Annotation.annotationType() 切换时也犯了错误。此代码有效
@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
请注意,这要求所有注释都标记为运行时级别保留,并且返回 Annotation[] 可能不是您想要的。您可能希望返回一个包含实际类型的 Class[](在我的示例中为 A.class)