[英]Java How to access private static member of class
Hi may I know how to access private static member outside Java classes?嗨,我可以知道如何访问 Java 类之外的私有静态成员吗?
I want to check if a value is set correctly.我想检查一个值是否设置正确。
(All necessary alerts about using reflection.) (有关使用反射的所有必要警报。)
Using reflection使用反射
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
is because the field is static, so there is no need in an instance of A
. null
是因为该字段是静态的,因此不需要A
的实例。
How to read the value of a private field from a different class in Java? 如何从 Java 中的不同类读取私有字段的值?
I've never used it, but I've heard that PowerMock is capable of testing private methods as well.我从未使用过它,但我听说 PowerMock 也能够测试私有方法。 https://github.com/powermock/powermock
https://github.com/powermock/powermock
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.