简体   繁体   中英

Java reflection multiple parameters

I am trying to use Java reflection and I have two different methods to call. One of them has a single String parameter and second one has two String parameters. I've managed to get first one working, but still struggling with the second one. I've checked references to two other questions ( Java reflection: getMethod(String method, Object[].class) not working and How to invoke method with variable arguments in java using reflection? ), but unfortunately had no luck with them. I keep getting the following exception:

java.lang.NoSuchMethodException: controllers.InventoryController.combineItems([Ljava.lang.String;)
at java.lang.Class.getMethod(Unknown Source)

Here is my working part of code:

Class[] paramString = new Class[1];
paramString[0] = String.class;
try {
    Class cls = this.getClass();

    Method method = cls.getDeclaredMethod(commandParts[0], paramString);
    method.invoke(this, new String(commandParts[1]));
} catch (Exception ex) {
    System.out.println("Doesn't work");
    ex.printStackTrace();
}

Now here is the part I can't get to work:

Class[] paramString = new Class[2];
paramString[0] = String[].class;

try {
    Class cls = this.getClass();

    Method method = cls.getMethod(commandParts[0], paramString[0]);
    method.invoke(this, new String[]{commandParts[1], commandParts[2]});
} catch (Exception ex) {
    System.out.println("Doesn't work");
    ex.printStackTrace();
}

What is the correct way of passing multiple parameters?

Error is because of

Method method = cls.getMethod(commandParts[0], paramString[0]);

this says return method name 'commandParts[0]' has only one parameter of type 'paramString[0]' change this with

Method method = cls.getMethod(commandParts[0], String.class, String.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM