设置私有静态字段的值 [英] Set Value of Private Static Field

查看:95
本文介绍了设置私有静态字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用反射来设置私有字段的值以进行单元测试。

I want to set the value of a private field using reflection for unit testing.

问题是,该字段是静态的。

Problem is, that field is static.

以下是我的工作:

/**
   * 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;
  }

我意识到这可能已经在SO上得到了答案,但我的搜索并没有把它打开......

I realize this has probably already been answered on SO, but my search didn't turn it up...

推荐答案

基本上问题是你的实用工具方法,假设你有一个实例。设置私有静态字段相当容易 - 除了指定 null 作为实例之外,它与实例字段完全相同。不幸的是,你的实用程序方法使用实例获取类,并要求它为非null ...

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();
    }
}

这篇关于设置私有静态字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆