Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java: Calling a method using reflection?

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!

like image 662
Jared Avatar asked Feb 04 '11 09:02

Jared


1 Answers

The following method will invoke the method and return true on success:

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");

like image 135
Gil SH Avatar answered Oct 26 '22 06:10

Gil SH