java 反射访问静态方法_如何使用反射(Java)调用私有静态方法?
我使用封裝獲取目標方法然后調用它的單個方法。當然可能有一些限制。這里是放入類中的方法和它的JUnit測試:
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));
}
}
}
總結
以上是生活随笔為你收集整理的java 反射访问静态方法_如何使用反射(Java)调用私有静态方法?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java treemap 内存_Java
- 下一篇: java中什么泛型_【原创】java中的