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

huangapple go评论82阅读模式
英文:

Java How to access private static member of class

问题

抱歉,您提供的内容似乎是关于访问Java类外部的私有静态成员以及验证数值是否正确设置的问题。以下是翻译好的部分:

"嗨,我能否知道如何在Java类之外访问私有静态成员?我想要检查一个值是否被正确设置。"

英文:

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

I want to check if a value is set correctly.

答案1

得分: 2

*(关于使用反射的所有必要警告)*

使用反射

    import java.lang.reflect.Field;
    
    public class Test {
        public static void main(String[] args) throws Exception {
    //      Class<A> clazz = A.class;            // 如果您在编译时知道类(静态地),即在编译时
            Class<?> clazz = Class.forName("A"); // 如果您在运行时动态知道类名,即在运行时
            Field field = clazz.getDeclaredField("x");
            field.setAccessible(true);
            System.out.println(field.getInt(null)); // 10
        }
    }
    
    class A {
        private static int x = 10;
    }

`null` 是因为该字段是静态的所以不需要 `A` 类的实例

https://stackoverflow.com/questions/1196192/how-to-read-the-value-of-a-private-field-from-a-different-class-in-java
英文:

(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&lt;A&gt; clazz = A.class;            // if you know the class statically i.e. at compile time
        Class&lt;?&gt; clazz = Class.forName(&quot;A&quot;); // if you know class name dynamically i.e. at runtime
        Field field = clazz.getDeclaredField(&quot;x&quot;);
        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.

https://stackoverflow.com/questions/1196192/how-to-read-the-value-of-a-private-field-from-a-different-class-in-java

答案2

得分: 1

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

英文:

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

huangapple
  • 本文由 发表于 2020年9月24日 03:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64035211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定