Reputation: 829
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?
Upvotes: 1
Views: 9175
Reputation: 3026
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);
Upvotes: 6