'Java 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?
Thanks
Solution 1:[1]
try this code sample:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.reflect.InvocationTargetException;
class AnotTest {
public static void main(String... args) {
AnnotationTest at = new AnnotationTest();
for (Method m : at.getClass().getMethods()) {
MethodXY mXY = (MethodXY)m.getAnnotation(MethodXY.class);
if (mXY != null) {
if (mXY.x() == 3 && mXY.y() == 2){
try {
m.invoke(at);
} catch (IllegalAccessException e) {
//do nothing;
} catch (InvocationTargetException o) {
//do nothing;
}
}
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
static public @interface MethodXY {
public int x();
public int y();
}
static class AnnotationTest {
@MethodXY(x=5, y=5)
public void myMethodA() {
System.out.println("boo");
}
@MethodXY(x=3, y=2)
public void myMethodB() {
System.out.println("foo");
}
}
}
Solution 2:[2]
private static final Method getMethodByAnnotation(Class<?> cla, Class<? extends Annotation> annotation,
int methodIndex) {
Stream<Method> stream = Arrays.stream(cla.getDeclaredMethods())
.filter(m -> m.isAnnotationPresent(annotation));
return methodIndex == 0 ? stream.findFirst().get() : stream.toArray(Method[]::new)[methodIndex];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dhblah |
| Solution 2 | Universe Whole-Xuan |
