简体   繁体   中英

Get a in a interface annotated method from class

I want to access Method via reflection. The problem is that the Method is annotated in an interface:

public interface MyRepository extends CrudRepository<MyClass, Long> {

    @CustomAnnotation
    MyClass findByName(String name);
}

As you see I use Spring which provides a class that will implement this Repository interface. I want to create a method, that will get a Repository and invoke all methods that are annotated with @CustomAnnotation .

public void do(Repository<?, ?> repository){
   Method[] methods=repository.getClass().getMethodThatAreAnnotatedInInterfaceWith(CustomAnnotation.class);
   ....
}

Because the implementation of an interface won't have the annotations of the interface present, I do not know how to query these methods.

Since you are using Spring, use the AnnotationUtils#findAnnotation(Method method, Class<A> annotationType) :

Find a single Annotation of annotationType on the supplied Method, traversing its super methods (ie, from superclasses and interfaces) if the annotation is not directly present on the given method itself.

Iterate over the methods of getClass().get[Declared]Methods() and for each of them check if it is annotated with your annotation using the above utility.

  1. Get the method of super class by repository.getClass().getDeclaredMethod().

  2. Get the interface of class by repository.getClass().getInterfaces().

  3. check the method of interface whether has the annotation.

One way to get a method's hierarchy would be to use Apache Commons Lang's class MethodUtils . Provided you get the implementation of a method you then can use that class to get (and check) the hierarchy of that method:

Set<Method> hierarchy = MethodUtils.getOverrideHierarchy( method, Interfaces.INCLUDE );

Then check the methods in that hierarchy for the annotation.

Alternatively you could check out the former Google Reflections library which has the method Reflections#getMethodsAnnotatedWith(SomeAnnotation.class) . You'd then use the returned set to check whether the actual implementation is an instance of the class/interface declaring those methods.

Here s the solution:

for (Class c : r.getClass().getInterfaces()) {
    for (Method m : c.getDeclaredMethods()) {
        if (m.getDeclaredAnnotation(CustomAnnotation.class) != null) {
            m.invoke(r, params);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM