[英]Java reflections - seek a method with specific annotation and its annotation element
假設我有這個注釋類
@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(){ ... }
}
那么,有沒有一種方法可以查看對象,使用@MethodXY注釋“查找”該方法,其元素x = 3,y = 2,並調用它?
使用核心Java Reflection已經在這里回答了這個問題。 我想知道是否可以使用Reflections 0.9.9-RC1 API做到這一點,而不必遍歷使用某些for循環代碼的方法或編寫一些直接比較方法,在該方法中我可以使用給定參數作為鍵或某些東西來搜索該方法。
當然,您可以使用Reflections#getMethodsAnnotatedWith()做到這一點。
您可以在這里找到答案。
這樣的事情會做的事情:
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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.