0

Hi may I know how to access private static member outside Java classes?

I want to check if a value is set correctly.

kaya3
  • 41,043
  • 4
  • 50
  • 79
Kallzvx
  • 493
  • 7
  • 17

2 Answers2

1

(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?

Dmytro Mitin
  • 37,305
  • 2
  • 20
  • 53
1

I've never used it, but I've heard that PowerMock is capable of testing private methods as well. https://github.com/powermock/powermock

MrBrightside
  • 119
  • 9