您好,我知道如何在Java类之外访问私有静态成员吗?
我要检查值是否设置正确。
答案 0 :(得分:1)
(有关使用反射的所有必要警报。)
使用反射
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Exception {
// Class<A> clazz = A.class; // if you know the class statically i.e. at compile time
Class<?> clazz = Class.forName("A"); // if you know class name dynamically i.e. at runtime
Field field = clazz.getDeclaredField("x");
field.setAccessible(true);
System.out.println(field.getInt(null)); // 10
}
}
class A {
private static int x = 10;
}
null
是因为该字段是静态的,所以在A
的实例中不需要。
How to read the value of a private field from a different class in Java?
答案 1 :(得分:1)
我从未使用过它,但是我听说PowerMock也能够测试私有方法。 https://github.com/powermock/powermock