Java Reflection Method Invoke invoke(Method method, Object instance, Object... parameters)

Here you can find the source of invoke(Method method, Object instance, Object... parameters)

Description

Invoke the method.

License

Open Source License

Parameter

Parameter Description
method The method that should be invoked.
instance The instance that should be passed.
parameters The parameters that should be passed.
T The return type.

Return

The return type.

Declaration

@SuppressWarnings("unchecked")
public static <T> T invoke(Method method, Object instance, Object... parameters) throws Throwable 

Method Source Code


//package com.java2s;
/*/*from  ww  w.j a v a  2s.  c o  m*/
 * AirBlock - Framework for Multi-Platform Minecraft-Plugins.
 * Copyright (C) 2014 stux!
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.*;

public class Main {
    /**
     * Invoke the method.
     * @param method      The method that should be invoked.
     * @param instance    The instance that should be passed.
     * @param parameters  The parameters that should be passed.
     * @param <T> The return type.
     * @return The return type.
     */
    @SuppressWarnings("unchecked")
    public static <T> T invoke(Method method, Object instance, Object... parameters) throws Throwable {
        if (!method.isAccessible())
            method.setAccessible(true);

        // Since static methods do not
        if (Modifier.isStatic(method.getModifiers()) && instance != null)
            instance = null;

        try {
            return (T) method.invoke(instance, parameters);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to invoke method", e);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }
}

Related

  1. invoke(Method m, Object o, String msg, Object... parameters)
  2. invoke(Method m, Object target, Object... params)
  3. invoke(Method method)
  4. invoke(Method method)
  5. invoke(Method method, Object data, Object... arguments)
  6. invoke(Method method, Object it, Object... args)
  7. invoke(Method method, Object javaBean, Object value)
  8. invoke(Method method, Object obj, Object... args)
  9. invoke(Method method, Object obj, Object... args)