简体   繁体   中英

Java reflections - seek a method with specific annotation and its annotation element

Suppose I have this annotation class

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodXY {
    public int x();
    public int y();
}

public class AnnotationTest {
    @MethodXY(x=5, y=5)
    public void myMethodA(){ ... }

    @MethodXY(x=3, y=2)
    public void myMethodB(){ ... }
}

So is there a way to look into an object, "seek" out the method with the @MethodXY annotation, where its element x = 3, y = 2, and invoke it?

This question is already answered here using core Java Reflection. I want to know if this can be done using Reflections 0.9.9-RC1 API without having to iterate over methods using some for loop code or by writing some direct comparision method where I can search the method with given parameters as a key or something.

Sure, you can do it with Reflections#getMethodsAnnotatedWith() .

You can find your answer here .

Something like this will do the thing:

public static Method findMethod(Class<?> c, int x, int y) throws NoSuchMethodException {
    for(Method m : c.getMethods()) {
        MethodXY xy = m.getAnnotation(MethodXY.class);
        if(xy != null && xy.x() == x && xy.y() == y) {
            return m;
        }
    }
    throw new NoSuchMethodException();
}

public static void main(String[] args) throws Exception {
    findMethod(AnnotationTest.class, 3, 2).invoke(new AnnotationTest());
    findMethod(AnnotationTest.class, 5, 5).invoke(new AnnotationTest());
}

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