Why do I get “object is not an instance of declaring class” when invoking a method using reflection?

前端 未结 2 1862
情深已故
情深已故 2020-12-16 09:35
public class Shared {

    public static void main(String arg[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, I         


        
相关标签:
2条回答
  • 2020-12-16 10:08

    When you invoke a method via reflection, you need to pass the object you are calling the method on as the first parameter to Method#invoke.

    // equivalent to s1.testParam("", obj)
    testParamMethod.invoke(s1, "", obj);
    
    0 讨论(0)
  • 2020-12-16 10:20
     testParamMethod.invoke("", obj); ///// here getting error
    

    The first parameter to invoke must be the object to invoke it on:

     testParamMethod.invoke(s1, "", obj); 
    
    0 讨论(0)
提交回复
热议问题