invoke Method via reflection and checking parameter - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke Method via reflection and checking parameter

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.text.TextUtils;

public class Main {
    private static final String TARGET_OBJECT = "target object: ";
    private static final String TARGET_OBJECT_CAN_NOT_BE_NULL = "target object can not be null";

    public static void invokeMethod(String methodName, Object target,
            Object... args) throws Exception {
        if (TextUtils.isEmpty(methodName)) {
            throw new RuntimeException("method name can not be empty");
        }/*from w w  w.j  ava2 s .  c  o  m*/
        if (target == null) {
            throw new RuntimeException(TARGET_OBJECT_CAN_NOT_BE_NULL);
        }
        List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
        for (Object arg : args) {
            parameterTypes.add(arg.getClass());
        }
        Method method = target.getClass().getDeclaredMethod(methodName,
                (Class<?>[]) parameterTypes.toArray());
        if (method == null) {
            throw new RuntimeException(TARGET_OBJECT
                    + target.getClass().getName()
                    + " do not have this method: " + methodName
                    + " with parameters: " + parameterTypes.toString());
        }
        method.setAccessible(true);
        method.invoke(target, args);
    }
}

Related Tutorials