2011-08-26 75 views
25
public class Shared { 

    public static void main(String arg[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { 
     Shared s1 = new Shared(); 

     Object obj[] = new Object[2]; 
     obj[0] = "object1"; 
     obj[1] = "object2"; 
     s1.testParam(null, obj); 

     Class param[] = new Class[2]; 
     param[0] = String.class; 
     param[1] = Object[].class; //// how to define the second parameter as array 
     Method testParamMethod = s1.getClass().getDeclaredMethod("testParam", param); 
     testParamMethod.invoke("", obj); ///// here getting error 
    } 

    public void testParam(String query,Object ... params){ 
     System.out.println("in the testparam method"); 
    } 

} 

這裏是輸出:當使用反射調用方法時,爲什麼我會得到「對象不是聲明類的實例」?

in the testparam method 
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(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at pkg.Shared.main(Shared.java:20) 

回答

48

當調用通過反射的方法,你需要傳遞要調用上作爲第一個參數,以Method#invoke方法的對象。

// equivalent to s1.testParam("", obj) 
testParamMethod.invoke(s1, "", obj); 
14
testParamMethod.invoke("", obj); ///// here getting error 

第一個參數來調用必須是對象調用它:

testParamMethod.invoke(s1, "", obj); 
相關問題