Android / Java: calling a method using reflection?

I have a static method called selectDialog (String s, int i) in which I want to call another method in the same class (Dialogs.class) based on the options provided for the Dialog selection. s is the name of the desired method, and I is the only parameter.

I tried many tutorials and spent several hours on this topic, but I can’t understand what exactly I need to do.

Any ideas?

Thanks!

+9
source share
4 answers

Why do you want to call a method with the name passed in the String parameter? Can you create constants for different actions, then use switch and in each case call the method with parameter i ?

You will have the advantage of a compiler that checks your code for errors.

edit: if you really want to use reflection, extract the Method object with:

 Method m = YourClass.class.getMethod("method_name",new Class[] { Integer.class }) 

I think Integer.class might work. Then call the method as

 m.invoke(null,123); //first argument is the object to invoke on, ignored if static method 
+16
source
 Method method = Dialogs.getMethod(s, Integer.class); method.invoke(null, i); 
+2
source

If you just want to call another static method in the class, you can use the approach already identified by others:

 Method method = Dialogs.getMethod(s, Integer.class); method.invoke(null, i); 

But if you want to use a static method to call a non-static method, you will need to pass the object you want to reference or make selectDialog non-static.

 function chooseDialog(Object o, String s, Integer i) { Method method = Dialogs.getMethod(o, Integer.class); method.invoke(o, i); } 

But I do not think that this is the right OOP way to deal with this problem. And based on your comments, reflection is not absolutely necessary and Dialog chose to analyze the string and pass that the appropriate method is a much more typical approach. In any case, your unit tests should look the same.

  if (s.equals("dialog1")) { dialog1(i); } 
+1
source

The following method will call the method and return true if successful:

 public static boolean invokeMethod(Object object,String methodName,Object... args) { Class[] argClasses = new Class[args.length]; try { Method m = object.getClass().getMethod(methodName,argClasses); m.setAccessible(true); m.invoke(object,args); return true; } catch (Exception ignore) { return false; } } 

Usage: invokeMethod(myObject,"methodName","argument1","argument2");

0
source

All Articles