Here you can find the source of invokeMethod(final Object obj, final Method method, final Object... args)
Parameter | Description |
---|---|
obj | - given object |
method | - given method |
args | - given arguments |
Parameter | Description |
---|---|
RuntimeException | if there is a problem while invoking the method. |
@SuppressWarnings("unchecked") public static <T> T invokeMethod(final Object obj, final Method method, final Object... args)
//package com.java2s; /************************************************************************ * This file is part of AdminCmd. * * AdminCmd 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. * * AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ import java.lang.reflect.Method; public class Main { /**//from w w w.j a v a2s . co m * Invoke the method with the given argument on the given object. Works also * for private method. * * @param obj * - given object * @param method * - given method * @param args * - given arguments * @return the result of the method. * @throws RuntimeException * if there is a problem while invoking the method. */ @SuppressWarnings("unchecked") public static <T> T invokeMethod(final Object obj, final Method method, final Object... args) { T result = null; method.setAccessible(true); try { result = (T) method.invoke(obj, args); } catch (final Exception e) { throw new RuntimeException("Can't invoke method " + method + " from " + obj, e); } finally { method.setAccessible(false); } return result; } }