1

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

I want to check if a value is set correctly.

kaya3
  • 47,440
  • 4
  • 68
  • 97
Kallzvx
  • 594
  • 7
  • 23

2 Answers2

2

(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
  • 48,194
  • 3
  • 28
  • 66
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
  • 1
  • 9