Hi may I know how to access private static member outside Java classes?
I want to check if a value is set correctly.
Hi may I know how to access private static member outside Java classes?
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
.
How to read the value of a private field from a different class in Java?
I've never used it, but I've heard that PowerMock is capable of testing private methods as well. https://github.com/powermock/powermock