Java Reflection Method Invoke invokeMethodAndGetRecursively(Object object, String methodName, Object... args)

Here you can find the source of invokeMethodAndGetRecursively(Object object, String methodName, Object... args)

Description

Invokes and returns result of method with given name and arguments of target object's class or one of it's superclasses.

License

Open Source License

Parameter

Parameter Description
object target object.
methodName name of the method.
args arguments.

Exception

Parameter Description
Exception an exception

Return

result of method invokation.

Declaration

public static Object invokeMethodAndGetRecursively(Object object, String methodName, Object... args)
        throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Method;

public class Main {
    /**/*from  ww  w . j  a v a 2s.  c  o m*/
     * Invokes and returns result of method with given name and arguments of target object's class or one of it's superclasses.
     * @param object target object.
     * @param methodName name of the method.
     * @param args arguments.
     * @return result of method invokation.
     * @throws Exception 
     */
    public static Object invokeMethodAndGetRecursively(Object object, String methodName, Object... args)
            throws Exception {
        Class clazz = object.getClass();
        boolean ended = false;
        do {
            for (Method m : clazz.getDeclaredMethods())
                if (m.getName().equalsIgnoreCase(methodName)) {
                    ended = true;
                    m.setAccessible(true);
                    try {
                        return m.invoke(object, args);
                    } finally {
                        m.setAccessible(false);
                    }
                }
            clazz = clazz.getSuperclass();
        } while (clazz != Object.class && !ended);
        throw new NullPointerException("There is no method with given name");
    }
}

Related

  1. invokeMethod(String className, String method, Class[] paramTypes, Object obj, Object[] args)
  2. invokeMethod(String methodName, Object gameCommand)
  3. invokeMethod(String name, Object target)
  4. invokeMethod2(Class cls, Object obj, String methodName, Object[] args)
  5. invokeMethodAndGet(Object object, String methodName, Object... args)
  6. invokeMethodAndReturn(Class clazz, String method, Object object)
  7. invokeMethodByName(@Nonnull T object, @Nonnull String name, Class typeArg, Object arg)
  8. invokeMethodByName(final Object obj, final String methodName, final Object[] args)
  9. invokeMethodHandleException(Method method, Object... args)