Here you can find the source of invoke(Object objToInvoke, Class> classToInvoke, String method, Class[] argumentClasses, Object[] arguments)
Parameter | Description |
---|---|
objToInvoke | The object you want to invoke |
classToInvoke | Which class owns the method |
method | The name of the method |
argumentClasses | The argument classes that should be passed to the method |
arguments | The arguments that should be passed to the method |
Parameter | Description |
---|---|
NoSuchMethodException | If the method name does not exist |
InvocationTargetException | If the underlying method throws an exception. |
IllegalAccessException | When the method can not be accessed |
public static Object invoke(Object objToInvoke, Class<?> classToInvoke, String method, Class[] argumentClasses, Object[] arguments) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
//package com.java2s; /******************************************************************************* * Copyright (c) 2017, i8c N.V. (Integr8 Consulting; http://www.i8c.be) * All Rights Reserved./* ww w . jav a 2 s . c om*/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { /** * Invoke a method via reflection * * @param objToInvoke The object you want to invoke * @param classToInvoke Which class owns the method * @param method The name of the method * @param argumentClasses The argument classes that should be passed to the method * @param arguments The arguments that should be passed to the method * * @return The return value of the method * * @throws NoSuchMethodException If the method name does not exist * @throws InvocationTargetException If the underlying method throws an exception. * @throws IllegalAccessException When the method can not be accessed */ public static Object invoke(Object objToInvoke, Class<?> classToInvoke, String method, Class[] argumentClasses, Object[] arguments) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method m = classToInvoke.getDeclaredMethod(method, argumentClasses); Object o; if (m.isAccessible()) o = m.invoke(objToInvoke, arguments); else { m.setAccessible(true); o = m.invoke(objToInvoke, arguments); m.setAccessible(false); } return o; } }