Java Method Call invoke(Object obj, String methodName, Object... args)

Here you can find the source of invoke(Object obj, String methodName, Object... args)

Description

This metho can help invoke the private method of the object, but it needs to cast the type of the result.

License

Open Source License

Parameter

Parameter Description
obj the object the underlying method is invoked from
methodName method name
args the arguments for the method to invoke

Exception

Parameter Description
Exception an exception

Return

result

Declaration

@SuppressWarnings("unchecked")
public static Object invoke(Object obj, String methodName, Object... args) throws Exception 

Method Source Code

//package com.java2s;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Main {
    /**/*ww  w  .  j av  a2s  . com*/
     * This metho can help invoke the private method of the object, but it needs
     * to cast the type of the result.
     *
     * @param obj
     *        the object the underlying method is invoked from
     * @param methodName
     *        method name
     * @param args
     *        the arguments for the method to invoke
     * @return
     *        result
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Object invoke(Object obj, String methodName, Object... args) throws Exception {

        Class[] types = new Class[args.length];
        Class tmp = null;
        for (int i = 0; i < types.length; i++) {
            tmp = args[i].getClass();
            if (Proxy.class.isAssignableFrom(tmp)) {
                if (tmp.getInterfaces() == null || tmp.getInterfaces().length == 0) {
                    if (!Proxy.class.isAssignableFrom(tmp.getSuperclass())) {
                        tmp = tmp.getSuperclass();
                    }
                } else {
                    tmp = tmp.getInterfaces()[0];
                }
            }
            types[i] = tmp;
        }
        Method method = obj.getClass().getDeclaredMethod(methodName, types);
        method.setAccessible(true);

        Object result = null;
        result = method.invoke(obj, args);
        return result;
    }
}

Related

  1. invoke(Object obj, String methodName)
  2. invoke(Object obj, String methodName, boolean newValue)
  3. invoke(Object obj, String methodName, Class argType, Object arg)
  4. invoke(Object obj, String methodName, Class clazz, Object newValue)
  5. invoke(Object obj, String methodName, Class[] parameterTypes, Object[] args)
  6. invoke(Object obj, String methodName, Object... params)
  7. invoke(Object obj, String methodName, Object[] params)
  8. invoke(Object obj, String name, Object... args)
  9. invoke(Object object, Method method)