so I have 2 methods, 1 with an argument the other without
command_hello(String sender);

I am trying to invoke the method using just their name:

I can do this by using the following for the method with no arguments:

Works! Great! But the moment I try
getClass().getMethod(cmds.get(cmd)).invoke(this, "Bob");

I get an java.lang.NoSuchMethodException.

Object invoke(Object obj, Object... args), where args are the args of the method I'm invoking and obj is where the method is invoked from.

Any suggestions? I tried casting "Bob" to an Object with no luck...

Edited by TheWhite: n/a

7 Years
Discussion Span
Last Post by TheWhite

Here I go figuring it out again. Hopefully this will get indexed and help someone else :)

Method getMethod(String name, Class<?>... parameterTypes), where name is the name of the method and paramaterTypes are the types for the arguments

Since "Bob" is a string and the argument is String person, I needed:
getClass().getMethod(cmds.get(cmd), String.class).invoke(this, "Bob");


Try using the fully qualified name, so something like:

invoke( new java.lang.String("Bob") )

nah, the problem was that I made parameterTypes null by not including it, so it only used the method with no parameters.

I did something clever to match the getMethod paramaterTypes to that of the ones I am using for invoke by doing:

String sender = "Bob";
this.getClass().getMethod(cmds.get(cmd),sender.getClass()).invoke(this, sender);

That way I only need to match it to the real function on the invoke side.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.