java - 从类中获取接口(interface)注释方法

标签 java spring reflection

我想通过反射访问方法。问题是方法在接口(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/

相关文章:

Spring Boot 和 FreeMarker

spring - 添加Spring安全标签库

java - 加载从目录中的 jar 扩展另一个类的类

java - Scala - 从 Java 反射性调用私有(private)静态方法

java - ModelClass.class.getDeclaredFields().length 在 Gradle Build 期间返回 4 但有 3 个声明的属性

Java JPA - 如何使用列表放置对象并使用 CRUD 更新列表对象?

java - JSF 1.2 : java. util.ConcurrentModificationException

Java ObjectInputStream 在读取原语时抛出 EOFException

java - JDBC 中大型 IN 子句的替代方案,如何使用 Java 中的表值参数?

java - 将方法参数从 String 更改为 int 时出错