Here you can find the source of invokeMethod(Class targetClass, Object obj, String methodName, Object arg)
Parameter | Description |
---|---|
target | Class Instance |
methodName | a parameter |
arg | a parameter |
public static Object invokeMethod(Class targetClass, Object obj, String methodName, Object arg)
//package com.java2s; import java.lang.reflect.Method; public class Main { /**//from w w w .j a v a 2 s.c o m * invoke Method * * @param target * Class * @param target * Class Instance * @param methodName * @param arg * @return */ public static Object invokeMethod(Class targetClass, Object obj, String methodName, Object arg) { Object result = null; try { Class argClasses[] = null; if (arg != null) argClasses = new Class[] { arg.getClass() }; Method method = getMethod(targetClass, methodName, argClasses); result = method.invoke(obj, new Object[] { arg }); } catch (Exception e) { // logger.debug(e); } return result; } /** * invoke Method * * @param obj * @param methodName * @param arg * @return Object */ public static Object invokeMethod(Object obj, String methodName, Object arg) { Class objClass = obj.getClass(); Object result = null; try { Class argClasses[] = null; if (arg != null) argClasses = new Class[] { arg.getClass() }; Method method = getMethod(objClass, methodName, argClasses); result = method.invoke(obj, new Object[] { arg }); } catch (Exception e) { // logger.debug(e); } return result; } /** * invoke Method * * @param obj * @param methodName * @param args * @return */ public static Object invokeMethod(Object obj, String methodName, Object args[]) { Class objClass = obj.getClass(); Object result = null; try { Class argClasses[] = null; if (args != null && args.length > 0) { argClasses = new Class[args.length]; for (int i = 0, max = args.length; i < max; i++) { argClasses[i] = (args[i] == null) ? null : args[i].getClass(); } } Method method = getMethod(objClass, methodName, argClasses); result = method.invoke(obj, args); } catch (Exception e) { // logger.debug(e); } return result; } /** * get Method * * @param objClass * @param methodName * @param argClass * @return Method * @throws Exception */ public static Method getMethod(Class objClass, String methodName, Class argClass) throws Exception { Class argClasses[] = (argClass == null) ? null : new Class[] { argClass }; return getMethod(objClass, methodName, argClasses); } /** * get Method * * @param objClass * @param methodName * @param argClasses * @return * @throws Exception */ public static Method getMethod(Class objClass, String methodName, Class argClasses[]) throws Exception { Method method = null; try { method = objClass.getDeclaredMethod(methodName, argClasses); } catch (Exception e) { } if (method == null) { try { method = objClass.getMethod(methodName, argClasses); } catch (Exception e) { // logger.debug(e); } } return method; } }