calls a method from its name a returns Object result if any - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

calls a method from its name a returns Object result if any

Demo Code


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import android.util.Log;

public class Main{
    private static boolean debug = true;
    /**//from   w  w  w  .  jav a 2  s.  com
     * callMethod() - calls a method from its name a returns Object result if
     * any
     * 
     * @param cl
     *            Parent class
     * @param obj
     *            Object on which the method is applied
     * @param mtd
     *            Method name
     * @param paramTypes
     *            Types of the parameters (null if none)
     * @param params
     *            Parameters (null if none)
     */
    public static Object callMethod(Class<?> cl, Object obj, String mtd,
            Class<?>[] paramTypes, Object[] params)
            throws IllegalArgumentException {
        Object ret = null;

        try {
            Method m = cl.getMethod(mtd, paramTypes);
            ret = m.invoke(obj, (Object[]) params);
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
        }

        return ret;
    }
}

Related Tutorials