Java Reflection Method Invoke invokeMethod(Object sourceObject, String methodName, Object... arguments)

Here you can find the source of invokeMethod(Object sourceObject, String methodName, Object... arguments)

Description

invoke Method

License

Open Source License

Declaration

public static Object invokeMethod(Object sourceObject, String methodName, Object... arguments) 

Method Source Code

//package com.java2s;
/* /* w w  w. ja  va2s .  c o  m*/
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.Method;

public class Main {
    public static Object invokeMethod(Object sourceObject, String methodName, Object... arguments) {
        Object returnValue;
        Method[] methodArray = sourceObject.getClass().getDeclaredMethods();
        Method metodo = null;
        for (Method m : methodArray) {
            if (m.getName().equals(methodName)) {
                metodo = m;
            }
        }

        if (metodo == null) {
            throw new RuntimeException("Couldn't find methos.");
        }

        metodo.setAccessible(true);
        try {
            returnValue = metodo.invoke(sourceObject, arguments);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't invoke method: " + methodName, e);
        }

        return returnValue;
    }
}

Related

  1. invokeMethod(Object objectInstance, String methodToInvoke, Class[] parameterTypes, Object[] instanceParameters)
  2. invokeMethod(Object owner, String methodName)
  3. invokeMethod(Object owner, String methodName, Object[] args)
  4. invokeMethod(Object parent, String method, Class[] paramTypes, Object[] args)
  5. invokeMethod(Object source, String method, Collection arguments)
  6. invokeMethod(Object target, Class clazz, String methodName, Class[] types, Object[] args)
  7. invokeMethod(Object target, Method method)
  8. invokeMethod(Object target, Method method)
  9. invokeMethod(Object target, Method method, Object... args)

  10. HOME | Copyright © www.java2s.com 2016