I use a single method that encapsulates the receipt of the target method and then calls it. There are probably some limitations, of course. Here is the method placed in the class and its JUnit test:
public class Invoker { public static final <T> Object invokeMethod(final String name, final T obj, final Class<?>[] types, final Object... args) throws Exception { Method method = obj.getClass().getDeclaredMethod(name, types); method.setAccessible(true); return method.invoke(obj, args); } @RunWith(JUnit4.class) public static class InvokerTest { @Test public void testInvoke() throws Exception { class TestTarget { private String hello() { return "Hello world!"; } } String actual = (String) Invoker.invokeMethod("hello", new TestTarget(), new Class<?>[] {}); String expected = "Hello world!"; assertThat(actual, is(expected)); } }
}
Josef.B Jan 14 '13 at 1:21 2013-01-14 01:21
source share