基本上,问题是您的实用程序方法,该方法假设您有一个实例。设置私有静态字段相当容易-
与实例字段完全相同,但您指定
null为实例除外。不幸的是,您的实用程序方法使用实例来获取类,并要求该类为非null …
我会回应汤姆的警告:不要那样做。如果这是您可以控制的类,那么我将创建一个包级方法:
void setFooForTesting(Bar newValue){ foo = newValue;}但是,如果您 确实 想要通过反射进行设置 ,那么 这里有一个完整的示例:
import java.lang.reflect.*;class FieldContainer{ private static String woot; public static void showWoot() { System.out.println(woot); }}public class Test{ // Declared to throw Exception just for the sake of brevity here public static void main(String[] args) throws Exception { Field field = FieldContainer.class.getDeclaredField("woot"); field.setAccessible(true); field.set(null, "New value"); FieldContainer.showWoot(); }}


