Java Reflection Method Invoke invokeMethod(final Method method, final Object instance, final Object... args)

Here you can find the source of invokeMethod(final Method method, final Object instance, final Object... args)

Description

invoke Method

License

Open Source License

Parameter

Parameter Description
method method to call
instance object instance to call method on
args optional arguments
T expected type of execution result

Return

method execution result

Declaration

@SuppressWarnings("unchecked")
public static <T> T invokeMethod(final Method method, final Object instance, final Object... args) 

Method Source Code

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

import java.lang.reflect.Method;

import java.util.Arrays;

public class Main {
    /**/*  ww  w  .  ja v a  2 s . c o  m*/
     * @param method   method to call
     * @param instance object instance to call method on
     * @param args     optional arguments
     * @param <T>      expected type of execution result
     * @return method execution result
     */
    @SuppressWarnings("unchecked")
    public static <T> T invokeMethod(final Method method, final Object instance, final Object... args) {
        final boolean acc = method.isAccessible();
        method.setAccessible(true);
        try {
            return (T) method.invoke(instance, args);
        } catch (Exception e) {
            throw new IllegalStateException(String.format("Failed to invoke method '%s#%s(%s)'",
                    method.getDeclaringClass(), method.getName(), Arrays.toString(args)), e);
        } finally {
            method.setAccessible(acc);
        }
    }
}

Related

  1. invokeMethod(Class clazz, E instance, String[] names, Object... args)
  2. invokeMethod(Class clazz, Object object, String methodName, Class[] parameterTypes, Object[] parameters)
  3. invokeMethod(Class clazz, String method, Class[] args, Object object, Object[] objects)
  4. invokeMethod(Class clz, String methodName, Object... params)
  5. invokeMethod(Class returnClass, String methodName, Object ivokeObject, Object... objects)
  6. invokeMethod(final Method method, final Object object)
  7. invokeMethod(final Method method, final Object object, final Object[] args)
  8. invokeMethod(final Object instance, final String methodName, final Class[] parTypes, final Object[] parameters)
  9. invokeMethod(final Object obj, final Method method, final Object... args)