1

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?

4
  • Have you tried: method.invoke(this, commandParts[1], commandParts[2]);? Commented Jul 31, 2013 at 10:15
  • Yes, no luck with that. Same error :-/ Commented Jul 31, 2013 at 10:17
  • what is the signature of the method you are trying to call? Commented Jul 31, 2013 at 10:18
  • its public void combineItems(String componentName1, String componentName2){//method body} Commented Jul 31, 2013 at 10:20

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.