Basically the problem is your utility method, which assumes you have an instance. It's reasonably easy to set a private static field - it's exactly the same procedure as for an instance field, except you specify null
as the instance. Unfortunately your utility method uses the instance to get the class, and requires it to be non-null...
I'd echo Tom's caveat: don't do that. If this is a class you have under your control, I'd create a package level method:
void setFooForTesting(Bar newValue)
{
foo = newValue;
}
However, here's a complete sample if you really, really want to set it with reflection:
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();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…