0

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.

Community
  • 1
  • 1
Mukund Jalan
  • 1,145
  • 20
  • 39
  • What did you try? This question looks *at the moment* too much like a code request –  May 29 '15 at 11:25
  • @RC I have taken set of methods with specified methods using reflections API but I have to iterate on the set to compare the parameters. i want to avoid the iteration if there is already a method available to the same. – Mukund Jalan May 29 '15 at 11:29
  • I'm pretty confident iterating over all annotated methods is mandatory in this case. –  May 29 '15 at 11:36
  • @RC I want something like Reflections#getMethodsAnnotatedWith(MethodXY.class,3,2) if you can suggest something useful – Mukund Jalan May 29 '15 at 11:38

2 Answers2

1

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

You can find your answer here.

Community
  • 1
  • 1
hammelion
  • 351
  • 2
  • 13
  • the `Reflections#getMethodsAnnotatedWith()` return set of annoted methods. I want something like `Reflections#getMethodsAnnotatedWith(MethodXY.class,3,2)` – Mukund Jalan May 29 '15 at 11:36
  • 1
    Using java8: getMethodsAnnotatedWith(MethodXY.class).stream().filter(method -> method.getAnnotation(MethodXY.class).getX() == 3 && method.getAnnotation(MethodXY.class).getY() == 2).map(method -> method.invoke(this)); This will find all methods with X=3 and Y=2 and invoke them. – hammelion May 30 '15 at 14:04
0

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());
}
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334