如何使用反射 (Java) 调用私有静态方法? [英] How do I invoke a private static method using reflection (Java)?
问题描述
我想调用一个私有静态方法.我有它的名字.我听说可以使用 Java 反射机制来完成.我该怎么做?
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?
我在尝试调用该方法时遇到的一个问题是如何指定其参数的类型.我的方法接收一个参数,它的类型是 Map.因此我不能做 Map
(在运行时,由于 Java 类型擦除,没有 Map 这样的东西).有没有其他方法获得方法?
One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE
(In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?
推荐答案
假设你想调用 MyClass.myMethod(int x);
Let's say you want to call MyClass.myMethod(int x);
Method m = MyClass.class.getDeclaredMethod("myMethod", Integer.TYPE);
m.setAccessible(true); //if security settings allow this
Object o = m.invoke(null, 23); //use null if the method is static
这篇关于如何使用反射 (Java) 调用私有静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!