Here you can find the source of invoke(Object target, String methodName, Object[] args)
public static Object invoke(Object target, String methodName, Object[] args)
//package com.java2s; /**/*from w ww. ja v a 2 s. c o m*/ * Copyright 1996-2014 FoxBPM ORG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author kenshin */ import java.lang.reflect.Method; public class Main { public static Object invoke(Object target, String methodName, Object[] args) { try { Class<? extends Object> clazz = target.getClass(); Method method = findMethod(clazz, methodName, args); method.setAccessible(true); return method.invoke(target, args); } catch (Exception e) { throw new RuntimeException("couldn't invoke " + methodName + " on " + target, e); } } private static Method findMethod(Class<? extends Object> clazz, String methodName, Object[] args) { for (Method method : clazz.getDeclaredMethods()) { // TODO add parameter matching if (method.getName().equals(methodName) && matches(method.getParameterTypes(), args)) { return method; } } Class<?> superClass = clazz.getSuperclass(); if (superClass != null) { return findMethod(superClass, methodName, args); } return null; } private static boolean matches(Class<?>[] parameterTypes, Object[] args) { if ((parameterTypes == null) || (parameterTypes.length == 0)) { return ((args == null) || (args.length == 0)); } if ((args == null) || (parameterTypes.length != args.length)) { return false; } for (int i = 0; i < parameterTypes.length; i++) { if ((args[i] != null) && (!parameterTypes[i].isAssignableFrom(args[i].getClass()))) { return false; } } return true; } }