2012-03-05 52 views
3

我正在使用反射來從用特定註釋註釋的類獲取方法。一旦我得到類中的方法列表,我循環遍歷這些方法,如果方法匹配特定的返回類型,我想調用該方法。出於測試目的,我知道我得到的方法返回一個字符串。使用反射調用方法時我傳遞了什麼對象

Reflections reflections = new Reflections(new ConfigurationBuilder() 
     .setScanners(new TypesScanner(), new TypeElementsScanner()) 
     .setUrls(ClasspathHelper.forPackage("stressball")) 
); 

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(DependantClass.class); 
System.out.println(annotated); 

for(Class<?> clazz : annotated) { 
    for(Method method : clazz.getMethods()) { 
     if(method.isAnnotationPresent(DependantResource.class)) { 
      if(method.getReturnType() == String.class) { 
       System.out.println(method.invoke(method,(Object[]) null)); 
      }     
     } 
    } 
} 

這是我試圖調用

@DependantResource 
public String showInjector() { 
    return "This is an injector"; 
} 

我不斷收到以下錯誤,我知道它有一切跟我傳遞到調用對象的方法,但該方法從循環而不是我應該傳遞的對象?

Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:616) 
at stressball.test.DefaultTest.main(DefaultTest.java:35) 

回答

4

這是不正確的:

method.invoke(method,(Object[]) null) 

你應該先實例化一個對象,然後撥打電話。例如:

method.invoke(clazz.newInstance(), (Object[]) null) 
+0

我知道這是簡單的事情......謝謝。 – ryandlf 2012-03-05 03:23:12

相關問題