2011-08-26 34 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"); 
    } 

} 

Đây là kết quả:Tại sao tôi nhận được "đối tượng không phải là một thể hiện khai báo lớp" khi gọi một phương thức sử dụng sự phản chiếu?

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) 

Trả lời

48

Khi bạn gọi một phương pháp thông qua phản ánh, bạn cần phải vượt qua các đối tượng bạn đang gọi phương thức trên là tham số đầu tiên Method#invoke.

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

Tham số đầu tiên để gọi phải là đối tượng để gọi nó vào lúc:

testParamMethod.invoke(s1, "", obj); 
Các vấn đề liên quan