Java Method Call invoke(Object object, String methodName, Object[] args)

Here you can find the source of invoke(Object object, String methodName, Object[] args)

Description

invoke

License

BSD License

Declaration

public static Object invoke(Object object, String methodName, Object[] args)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException 

Method Source Code

//package com.java2s;
/**/*from ww  w .  ja  v a 2s.com*/
 * License
 * ProxyToys is open source software, made available under a BSD license.
 * 
 * Copyright (c) 2003-2005, 2009, 2010 Thoughtworks Ltd. 
 * Written by Dan North, Aslak Helles?y, J?rg Schaible, Paul Hammant.
 * 
 * 
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer. Redistributions in binary form must reproduce
 * the above copyright notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of proxytoys nor the names of its contributors may be used to endorse
 * or promote products derived from this software without specific prior written
 * permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
 * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 * 
 */

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

import java.util.HashSet;
import java.util.Set;

public class Main {
    public static Object invoke(Object object, String methodName, Object[] args)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        if (object == null) {
            throw new NullPointerException();
        }
        Method method = getMatchingMethod(object.getClass(), methodName, args);
        return method.invoke(object, args);
    }

    /**
     * Get the method of the given type, that has matching parameter types to
     * the given arguments.
     * 
     * @param type
     *            the type
     * @param methodName
     *            the name of the method to search
     * @param args
     *            the arguments to match
     * @return the matching {@link Method}
     * @throws NoSuchMethodException
     *             if no matching {@link Method} exists
     * @since 0.2
     */
    public static Method getMatchingMethod(final Class type, final String methodName, final Object[] args)
            throws NoSuchMethodException {
        final Object[] newArgs = args == null ? new Object[0] : (Object[]) args;
        final Method[] methods = type.getMethods();
        final Set possibleMethods = new HashSet();
        Method method = null;
        for (int i = 0; method == null && i < methods.length; i++) {
            if (methodName.equals(methods[i].getName())) {
                final Class[] argTypes = methods[i].getParameterTypes();
                if (argTypes.length == newArgs.length) {
                    boolean exact = true;
                    Method possibleMethod = methods[i];
                    for (int j = 0; possibleMethod != null && j < argTypes.length; j++) {
                        final Class newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class;
                        if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class))
                                || (argTypes[j].equals(char.class) && newArgType.equals(Character.class))
                                || (argTypes[j].equals(short.class) && newArgType.equals(Short.class))
                                || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class))
                                || (argTypes[j].equals(long.class) && newArgType.equals(Long.class))
                                || (argTypes[j].equals(float.class) && newArgType.equals(Float.class))
                                || (argTypes[j].equals(double.class) && newArgType.equals(Double.class))
                                || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) {
                            exact = true;
                        } else if (!argTypes[j].isAssignableFrom(newArgType)) {
                            possibleMethod = null;
                            exact = false;
                        } else if (!argTypes[j].isPrimitive()) {
                            if (!argTypes[j].equals(newArgType)) {
                                exact = false;
                            }
                        }
                    }
                    if (exact) {
                        method = possibleMethod;
                    } else if (possibleMethod != null) {
                        possibleMethods.add(possibleMethod);
                    }
                }
            }
        }
        if (method == null && possibleMethods.size() > 0) {
            method = (Method) possibleMethods.iterator().next();
        }
        if (method == null) {
            final StringBuffer name = new StringBuffer(type.getName());
            name.append('.');
            name.append(methodName);
            name.append('(');
            for (int i = 0; i < newArgs.length; i++) {
                if (i != 0) {
                    name.append(", ");
                }
                // FIXME here fix a NullPointerException bug. if somebody
                // passed a null parameter in the newArgs, there will be a
                // NullPointerException. fixed by Xiaoyi Lu at 2009-02-26.
                if (newArgs[i] != null) {
                    name.append(newArgs[i].getClass().getName());
                } else {
                    name.append("null");
                }
            }
            name.append(')');
            throw new NoSuchMethodException(name.toString());
        }
        return method;
    }
}

Related

  1. invoke(Object object, String function, String parameter)
  2. invoke(Object object, String method, Object... args)
  3. invoke(Object object, String methodName)
  4. invoke(Object object, String methodName, Class[] argTypes, Object... args)
  5. invoke(Object object, String methodName, Class returnType, Object... parameters)
  6. invoke(Object objToInvoke, Class classToInvoke, String method, Class[] argumentClasses, Object[] arguments)
  7. invoke(Object owner, String methodName)
  8. invoke(Object proxy, java.lang.reflect.Method method, Object[] args)
  9. invoke(Object source, String key)