Java Reflection Method Invoke invokeMethod(Object object, String methodName, Object... parameters)

Here you can find the source of invokeMethod(Object object, String methodName, Object... parameters)

Description

Invokes the method with the given name of the specified object, with the specified parameters.

License

Open Source License

Parameter

Parameter Description
T a parameter
object the object
methodName the
parameters the parameters

Return

the method return value of the dispatched method

Declaration

public static <T> T invokeMethod(Object object, String methodName, Object... parameters) 

Method Source Code

//package com.java2s;
/*//from w  w w  .  ja  v  a 2s  .c om
 * Copyright Ericsson AB 2011-2014. All Rights Reserved.
 *
 * The contents of this file are subject to the Lesser GNU Public License,
 *  (the "License"), either version 2.1 of the License, or
 * (at your option) any later version.; you may not use this file except in
 * compliance with the License. You should have received a copy of the
 * License along with this software. If not, it can be
 * retrieved online at https://www.gnu.org/licenses/lgpl.html. Moreover
 * it could also be requested from Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
 * WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
 * EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
 * OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND,
    
 * EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
 * LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE,
 * YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 *
 * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
 * WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
 * REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
 * DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
 * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY
 * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
 * INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE
 * OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH
 * HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 */

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Main {
    /**
     * Invokes the method with the given name of the specified object, with the
     * specified parameters. If the object is a class, then it is assumed to be
     * a static method.
     *
     * @param <T>
     * @param object the object
     * @param methodName the
     * @param parameters the parameters
     *
     * @return the method return value of the dispatched method
     */
    public static <T> T invokeMethod(Object object, String methodName, Object... parameters) {
        try {
            Class[] parameterTypes = new Class[parameters.length];
            for (int i = 0; i < parameters.length; i++) {
                Object arg = parameters[i];
                parameterTypes[i] = arg.getClass();
            }
            Method method;
            if (object instanceof Class) {
                method = findMethod((Class) object, methodName, parameterTypes);
                object = null;
            } else {
                method = findMethod(object.getClass(), methodName, parameterTypes);
            }
            method.setAccessible(true);
            return (T) method.invoke(object, parameters);
        } catch (IllegalAccessException | IllegalArgumentException | SecurityException
                | InvocationTargetException e) {
            throw new Error(e);
        }
    }

    /**
     * Attempt to find a {@link Method} on the supplied class with the supplied
     * name and parameter types. Searches all superclasses up to
     * <code>Object</code>.
     * <p>
     * Returns <code>null</code> if no {@link Method} can be found.
     *
     * @param clazz the class to introspect
     * @param name the name of the method
     * @param paramTypes the parameter types of the method (may be
     * <code>null</code> to indicate any signature)
     *
     * @return the Method object, or <code>null</code> if none found
     */
    private static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
        Class<?> searchType = clazz;
        while (searchType != null) {
            Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                    : searchType.getDeclaredMethods());
            for (Method method : methods) {
                if (name.equals(method.getName())
                        && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                    return method;
                }
            }
            searchType = searchType.getSuperclass();
        }
        return null;
    }
}

Related

  1. invokeMethod(Object object, Method method, Object... args)
  2. invokeMethod(Object object, String methodName, Class[] parameterTypes, Object[] parameters)
  3. invokeMethod(Object object, String methodName, Class[] signature, Object[] parameters)
  4. invokeMethod(Object object, String methodName, List argList)
  5. invokeMethod(Object object, String methodName, Object arg, Class argType)
  6. invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)
  7. invokeMethod(Object object, String methodName, Object[] params, Object[] result)
  8. invokeMethod(Object object, String name, Object... arguments)
  9. invokeMethod(Object object, String propertyName)