2个方法被同一个注释所修饰,仅仅是注释的参数不同
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");
}
}
}
原文: http://stackoverflow.com/questions/6593597/java-seek-a-method-with-specific-annotation-and-its-annotation-element