How do I invoke a private static method using reflection (Java)?

前端 未结 5 446
[愿得一人]
[愿得一人] 2020-11-29 03:32

I would like to invoke a private static method. I have its name. I\'ve heard it can be done using Java reflection mechanism. How can I do it?

EDIT:

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 03:56

    I use a single method that encapsulates getting the target method and then invoking it. Probably has some limitations, of course. Here is the method put into a class and its JUnit test:

    public class Invoker {
    /**
     * Get method and invoke it.
     * 
     * @author jbetancourt
     * 
     * @param name of method
     * @param obj Object to invoke the method on
     * @param types parameter types of method
     * @param args to method invocation
     * @return return value
     * @throws Exception for unforseen stuff
     */
    public static final  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);
    }
    
    /**
     * Embedded JUnit tests.
     */
    @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));
    
        }
    }
    

    }

提交回复
热议问题