Here you can find the source of invoke(final Object instance, final String method, final Object... parameters)
Parameter | Description |
---|---|
instance | to inspect |
method | the name of the method to be invoked |
parameters | the instances used to fill the parameters |
Parameter | Description |
---|---|
Throwable | in case anything goes wrong |
public static Object invoke(final Object instance, final String method, final Object... parameters) throws Throwable
//package com.java2s; //License from project: Open Source License import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; public class Main { /**/* w ww.j a v a 2s . c om*/ * Execute a method by reflection. * * @param instance * to inspect * @param method * the name of the method to be invoked * @param parameters * the instances used to fill the parameters * @return the result of the method invoked * @throws Throwable * in case anything goes wrong */ public static Object invoke(final Object instance, final String method, final Object... parameters) throws Throwable { final Class<?> clazz = instance.getClass(); for (final Method m : clazz.getMethods()) { if (m.getName().equals(method)) { try { return m.invoke(instance, parameters); } catch (final IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("Can't invoke method", e); } catch (final InvocationTargetException e) { throw e.getTargetException(); } } } throw new RuntimeException("Can't find method"); } /** * Execute a method by reflection. * * @param instance * to inspect * @param method * the name of the method to be invoked * @param paramTypes * the class types used as parameter * @param parameters * the instances used to fill the parameters * @return the result of the method invoked */ public static Object invoke(final Object instance, final String method, final Class<?>[] paramTypes, final Object... parameters) { final Class<?> clazz = instance.getClass(); for (final Method m : clazz.getMethods()) { if (m.getName().equals(method) && Arrays.equals(m.getParameterTypes(), paramTypes)) { try { return m.invoke(instance, parameters); } catch (final Exception e) { throw new RuntimeException("Can't invoke method", e); } } } throw new RuntimeException("Can't find method"); } }