英文:
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<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
.
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论