Java Reflection Method Invoke invokeMethod(Object target, String method)

Here you can find the source of invokeMethod(Object target, String method)

Description

invokes the given method to the given target using reflection.

License

Apache License

Return

the value returned by the invoked method.

Declaration

public static Object invokeMethod(Object target, String method) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

import com.google.common.base.Function;

public class Main {
    /**// ww w .  j a v a 2 s.c om
     * invokes the given method to the given target using reflection.
        
     * @return the value returned by the invoked method.
     */
    public static Object invokeMethod(Object target, String method) {
        return getMethodInvoker(method).apply(target);
    }

    /**
     * @return a function that invokes the given method using reflection.
     */
    public static Function<Object, Object> getMethodInvoker(final String methodName) {
        return getMethodInvoker(Object.class, methodName);
    }

    /**
     * @return a function that invokes the given method using reflection and will cast it to the given return type.
     */
    public static <T> Function<Object, T> getMethodInvoker(final Class<T> returnType, final String methodName) {
        return new Function<Object, T>() {
            public T apply(Object from) {
                if (from == null)
                    return null;
                try {
                    Method method = from.getClass().getMethod(methodName, new Class[0]);
                    return returnType.cast(method.invoke(from, new Object[0]));
                } catch (SecurityException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException(e);
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }
}

Related

  1. invokeMethod(Object target, Class clazz, String methodName, Class[] types, Object[] args)
  2. invokeMethod(Object target, Method method)
  3. invokeMethod(Object target, Method method)
  4. invokeMethod(Object target, Method method, Object... args)
  5. invokeMethod(Object target, Method method, Object[] args)
  6. invokeMethod(Object target, String methodName, Object... parameters)
  7. invokeMethod(Object target, String methodName, Object[] arguments)
  8. invokeMethod(Object target, String name, Class... parameterTypes)
  9. invokeMethod(Object target, String name, Object[] args, Class[] argTypes)