Here you can find the source of invokeMethodAndReturn(Class> clazz, String method, Object object)
public static Object invokeMethodAndReturn(Class<?> clazz, String method, Object object)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static Object invokeMethodAndReturn(Method method, Object instance) { Object ret;/*www .j a v a 2s. c o m*/ try { method.setAccessible(true); ret = method.invoke(instance); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { ret = null; } return ret; } public static Object invokeMethodAndReturn(Method method, Object instance, Object[] params) { Object ret; try { method.setAccessible(true); ret = method.invoke(instance, params); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { ret = null; } return ret; } public static Object invokeMethodAndReturn(Class<?> clazz, String method, Object object) { Object value = null; try { Method methodToInvoke = getMethod(clazz, method); methodToInvoke.setAccessible(true); value = methodToInvoke.invoke(object); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return value; } public static Object invokeMethodAndReturn(Class<?> clazz, String method, Object object, Object... params) { Object value = null; Class<?>[] args = new Class<?>[params.length]; for (int x = 0; x < params.length; x++) { args[x] = params[x].getClass(); } try { Method methodToInvoke = getMethod(clazz, method, args); methodToInvoke.setAccessible(true); value = methodToInvoke.invoke(object, params); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return value; } public static Method getMethod(Class<?> clazz, String method, Class<?>[] args) { for (Method m : clazz.getMethods()) { if (m.getName().equals(method) && classListEqual(args, m.getParameterTypes())) { return m; } } return null; } public static Method getMethod(Class<?> clazz, String method, Integer args) { for (Method m : clazz.getMethods()) { if (m.getName().equals(method) && args.equals(Integer.valueOf(m.getParameterTypes().length))) { return m; } } return null; } public static Method getMethod(Class<?> clazz, String method) { for (Method m : clazz.getMethods()) { if (m.getName().equals(method)) { return m; } } return null; } public static boolean classListEqual(Class<?>[] listOne, Class<?>[] listTwo) { if (listOne.length != listTwo.length) { return false; } for (int i = 0; i < listOne.length; i++) { if (listOne[i] != listTwo[i] && (listTwo[i].isAssignableFrom(listOne[i]) == false)) { return false; } } return true; } }