invoke Method by Object, method name and arguments - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke Method by Object, method name and arguments

Demo Code


//package com.java2s;
import java.lang.reflect.Method;

public class Main {
    public static Object invokeMethod(Object owner, String methodName,
            Object[] args) {/*ww  w . j ava 2s . co m*/
        Class ownerClass = owner.getClass();
        Class[] argsClass = (args != null) ? new Class[args.length] : null;
        if (argsClass != null) {
            for (int i = 0, j = args.length; i < j; i++) {
                argsClass[i] = args[i].getClass();
            }
        }
        try {
            Method method = ownerClass.getMethod(methodName, argsClass);
            return method.invoke(owner, args);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials