我想通过反射访问方法。问题是方法在接口(interface)中被注释:
public interface MyRepository extends CrudRepository<MyClass, Long> {
@CustomAnnotation
MyClass findByName(String name);
}
如您所见,我使用 Spring,它提供了一个将实现此 Repository 接口(interface)的类。
我想创建一个方法,它将获取一个存储库并调用所有用 @CustomAnnotation
注释的方法。
public void do(Repository<?, ?> repository){
Method[] methods=repository.getClass().getMethodThatAreAnnotatedInInterfaceWith(CustomAnnotation.class);
....
}
因为接口(interface)的实现不会有接口(interface)的注解存在,不知道如何查询这些方法。
最佳答案
由于您使用的是 Spring,因此请使用 AnnotationUtils#findAnnotation(Method method, Class<A> annotationType)
:
Find a single Annotation of annotationType on the supplied Method, traversing its super methods (i.e., from superclasses and interfaces) if the annotation is not directly present on the given method itself.
遍历 getClass().get[Declared]Methods()
的方法并使用上述实用程序检查它们中的每一个是否用您的注释进行了注释。
关于java - 从类中获取接口(interface)注释方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014539/