[英]java.lang.IllegalAccessException:.cannot access the member of class CrossOrigin with modifiers "private static"
[英]Java How to access private static member of class
嗨,我可以知道如何訪問 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
的實例。
我從未使用過它,但我聽說 PowerMock 也能夠測試私有方法。 https://github.com/powermock/powermock
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.