Java Reflection Method Return getMethodInvoker(final Class returnType, final String methodName)

Here you can find the source of getMethodInvoker(final Class returnType, final String methodName)

Description

get Method Invoker

License

Apache License

Return

a function that invokes the given method using reflection and will cast it to the given return type.

Declaration

public static <T> Function<Object, T> getMethodInvoker(final Class<T> returnType, final String methodName) 

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 {
    /**/*from  w w w  .j  ava  2s  .co  m*/
     * @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. getMethodDesc(Class returnType, Class... params)
  2. getMethode(Class clasS, Class Returntype, int modifier, Class... classes)
  3. getMethodGenericReturnType(Method method, Class rawType, int index)
  4. getMethodGenericReturnType(Method method, int index)
  5. getMethodGenericReturnType(Method method, int index)
  6. getMethodNoArgs(final Class objClass, final String methodName, final Class... returnTypePreference)
  7. getMethodReturnType(Class clazz, String methodName)
  8. getMethodReturnType(Class clazz, String name)
  9. getMethodReturnType(Class clazz, String name)