Java Method Call invoke(E e, String methodName)

Here you can find the source of invoke(E e, String methodName)

Description

invoke

License

Apache License

Declaration

public static <E> Object invoke(E e, String methodName) 

Method Source Code

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

import java.lang.reflect.Method;

public class Main {
    public static <E> Object invoke(E e, String methodName) {
        return invoke(e, methodName, new Object[0]);
    }/* w w w  .j  a va 2  s. c  om*/

    @SuppressWarnings("unchecked")
    public static <E> Object invoke(E e, String methodName, Object... params) {
        Class<E> clazz = (Class<E>) e.getClass();
        try {
            Method method = clazz.getDeclaredMethod(methodName, paramsClasses(params));
            method.setAccessible(true);
            return method.invoke(e, params);
        } catch (Exception ex) {
            throw new RuntimeException("Cannot execute " + methodName, ex);
        }
    }

    private static Class<?>[] paramsClasses(Object... params) {
        if (params == null || params.length == 0) {
            return new Class<?>[0];
        }
        Class<?>[] classez = new Class<?>[params.length];
        for (int i = 0; i < params.length; i++) {
            Object obj = params[i];
            if (obj == null) {
                classez[i] = null;
            } else {
                classez[i] = obj.getClass();
            }
        }
        return classez;
    }
}

Related

  1. invoke(Class clazz, Object obj, String methodName, Object... args)
  2. invoke(Class clazz, String methodName, Class[] parameterTypes, Object instance, Object[] args, Class returnType)
  3. invoke(Class clazz, String methodName, Object instance, Class[] signature, Object... args)
  4. invoke(Class cls, String methodName, Object... parameter)
  5. invoke(Class returnType, Method m, Object obj, Object... args)
  6. invoke(final Method m, final Object obj, final Object... args)
  7. invoke(final Method method, final Object obj, final Object... args)
  8. invoke(final Object component, final Method method, final Class type, final String value)
  9. invoke(final Object instance, final String method, final Object... parameters)