Java如何访问类的私有静态成员

问题描述

您好,我知道如何在Java类之外访问私有静态成员吗​​?

我要检查值是否设置正确。

解决方法

(有关使用反射的所有必要警报。)

使用反射

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?

,

我从未使用过它,但是我听说PowerMock也能够测试私有方法。 https://github.com/powermock/powermock

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...