invoke Method from Object and method name - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke Method from Object and method name

Demo Code


import android.content.Context;
import android.util.Log;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main{
    private static final String TAG = ReflectionUtils.class.getSimpleName();
    public static void invokeMethod(Object object, String methodName) {
        invokeMethod(object, methodName, null, null);
    }/*  ww w  . j  a  va 2s .  com*/
    public static void invokeMethod(Object object, String methodName,
            Object[] types, Object[] values) {

        Method method = getMethod(object, methodName, types);
        if (method != null) {
            try {
                method.invoke(object, values);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }
    public static Method getMethod(Object object, String methodName,
            Object[] types) {
        Method method = null;
        try {

            Class<?>[] typeClassArray = null;

            if (types != null && types.length > 0) {
                typeClassArray = new Class<?>[types.length];

                for (int i = 0; i < types.length; i++) {
                    typeClassArray[i] = (Class<?>) types[i];
                }

            } else {
                typeClassArray = new Class<?>[] {};
            }

            method = object.getClass()
                    .getMethod(methodName, typeClassArray);

        } catch (NoSuchMethodException e) {
            Log.w(TAG, "Method \"" + methodName + "\" not found for "
                    + object.getClass().toString());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return method;
    }
    public static Class<?> getClass(Context context, String className) {
        Class<?> classDefinition = null;
        if (className.contains(context.getPackageName())) {
            classDefinition = getClass(className);
        } else {
            classDefinition = getClass(context.getPackageName() + className);
        }
        return classDefinition;
    }
    public static Class<?> getClass(String className) {
        Class<?> classDefinition = null;
        try {
            classDefinition = Class.forName(className);
        } catch (ClassNotFoundException e) {
            Log.w(TAG, "Class \"" + className + "\" not found");
        }
        return classDefinition;
    }
}

Related Tutorials