call method using reflection by method name - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

call method using reflection by method name

Demo Code


import android.text.TextUtils;
import android.util.Log;
import java.lang.reflect.Method;

public class Main{
    private static final String TAG = ReflectionUtils.class.getSimpleName();
    public static <T> T call(Object instance, String methodName) {
        try {/*from  w  w  w.j a v a2 s  .com*/
            Class cmClass = Class.forName(instance.getClass().getName());
            Method method = cmClass.getDeclaredMethod(methodName);
            method.setAccessible(true); // Make the method callable
            // get the setting for "mobile data"
            return (T) method.invoke(instance);
        } catch (Exception e) {
            Log.e(TAG, "Exception calling method: ", e);
        }
        return null;
    }
}

Related Tutorials