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

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

I can do this by using the following for the method with no arguments:
getClass().getMethod("command_hello").invoke(this);

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...

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.