您可以遍历所有超类和接口的超方法来查找注释。但是您可能会发现多个注释,因为该方法可能在多个类或接口中声明。
以下是我的示例代码:
public class Q46553516 {
public static void main(String[] args) throws Exception {
// the input method
Method method = ClassB.class.getMethod("func");
// get the annotation value
Class<?> clz = method.getDeclaringClass();
List<Anno> collect = Stream.concat(
Stream.of(clz),
Stream.concat(
Stream.of(ReflectUtil.getAllSuperClasses(clz)),
Stream.of(ReflectUtil.getAllInterfaces(clz))))
.map(c -> {
try {
return c.getMethod(method.getName(), method.getParameterTypes());
} catch (Exception e) {
return null;
}
})
.filter(m -> m != null)
.map(m -> m.getAnnotation(Anno.class))
.filter(a -> a != null)
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Inherited
public @interface Anno {
String value();
}
static interface Inter {
@Anno("Inter")
void func();
}
static class ClassA implements Inter {
@Override
@Anno("ClassA")
public void func() {
}
}
static class ClassB extends ClassA {
@Override
public void func() {
}
}
}
@xdean.stackoverflow.java.reflection.Q46553516$MyCheck(feature=ClassA)
@xdean.stackoverflow.java.reflection.Q46553516$MyCheck(feature=Inter)
ReflectUtil
,你可以找到它
here