I have a static method titled chooseDialog(String s, int i) in which I want to call another method within the same class (Dialogs.class) based on the parameters provided to chooseDialog. s is the name of the desired method and i is it's single parameter.
I have tried numerous tutorials and have spent a few hours reading up on the subject but I can't seem to get a firm grasp as to what exactly I need to do.
Any ideas?
Thanks!
If you just want to call another static method on the class, then you can use the approach already identified by others:
But if you want to be able to use a static method to call an non-static method, then you will need to pass in the object that you want to reference or make chooseDialog non-static.
But I don't think that this is the correct OOP way to handle the problem. And based on your comments, reflection isn't absolutely necessary, and have chooseDialog analyze the string and pass that to the appropriate method is a much more typesafe approach. In either approach, your unit tests should look the same.
Why do you want to call a method with name passed in a String parameter? Cannot you create a constants for different actions, then use
switch
and in each case call the method with parameteri
?You will have the benefit of compiler checking your code for errors.
edit: if you really want to use reflection, retrieve a
Method
object with:I guess Integer.class might work. Then invoke the metod as
The following method will invoke the method and return true on success:
Usage:
invokeMethod(myObject,"methodName","argument1","argument2");