Invoke method with an array parameter using reflection

后端 未结 3 1439
不知归路
不知归路 2021-01-17 11:25

I am attempting to write a method the executes a static method from another class by passing an array of strings as arguments to the method.

Here\'s what I have:

相关标签:
3条回答
  • 2021-01-17 11:53

    The method your trying to invoke is expecting String array, however you are passing Object array as param. Change it to String array Or you can pass any type if the method expects Object.

    method.invoke(null,(Object) command );

    0 讨论(0)
  • 2021-01-17 11:58

    Based on this question, it looks like the call should be

     method.invoke(null, command);
    
    0 讨论(0)
  • 2021-01-17 12:00

    You have two problems:

    1. The target parameter type is String[], but you're passing in a Object[]
    2. You're passing in the whole command array as arguments, which includes the method name

    The problems are all in the inner try block, so I show only that code.

    String[] args = Arrays.copyOfRange(command, 1, command.length - 1);
    method.invoke(null, new Object[]{args}); // must prevent expansion into varargs
    

    Thanks to Perception for reminding me of the varargs issue

    0 讨论(0)
提交回复
热议问题