Java 设置私有静态字段的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3239039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Value of Private Static Field
提问by Tom Tresansky
I want to set the value of a private field using reflection for unit testing.
我想使用反射来设置私有字段的值进行单元测试。
Problem is, that field is static.
问题是,该字段是静态的。
Here's what I'm working from:
这是我的工作内容:
/**
* Use to set the value of a field you don't have access to, using reflection, for unit testing.
*
* Returns true/false for success/failure.
*
* @param p_instance an object to set a private field on
* @param p_fieldName the name of the field to set
* @param p_fieldValue the value to set the field to
* @return true/false for success/failure
*/
public static boolean setPrivateField(final Object p_instance, final String p_fieldName, final Object p_fieldValue) {
if (null == p_instance)
throw new NullPointerException("p_instance can't be null!");
if (null == p_fieldName)
throw new NullPointerException("p_fieldName can't be null!");
boolean result = true;
Class<?> klass = p_instance.getClass();
Field field = null;
try {
field = klass.getDeclaredField(p_fieldName);
field.setAccessible(true);
field.set(p_instance, p_fieldValue);
} catch (SecurityException e) {
result = false;
} catch (NoSuchFieldException e) {
result = false;
} catch (IllegalArgumentException e) {
result = false;
} catch (IllegalAccessException e) {
result = false;
}
return result;
}
I realize this has probably already been answered on SO, but my search didn't turn it up...
我意识到这可能已经在 SO 上得到了回答,但是我的搜索并没有出现......
采纳答案by Jon Skeet
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...
基本上问题在于您的实用程序方法,它假设您有一个实例。设置私有静态字段相当容易 - 除了您指定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, reallywant 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();
}
}
回答by Vivin Paliath
Just pass null
for the object-instance argument. So:
只需传递null
对象实例参数。所以:
field.set(null, p_fieldValue);
This will let you set the static field.
这将让您设置静态字段。