Here you can find the source of invoke(Object obj, String methodName, Object... args)
Parameter | Description |
---|---|
obj | the object the underlying method is invoked from |
methodName | method name |
args | the arguments for the method to invoke |
Parameter | Description |
---|---|
Exception | an exception |
@SuppressWarnings("unchecked") public static Object invoke(Object obj, String methodName, Object... args) throws Exception
//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; } }