有没有办法在Java中重新初始化静态类? [英] Is there a way to reinitialize a static class in Java?

查看:689
本文介绍了有没有办法在Java中重新初始化静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对一个引用另一个类的静态数据的类进行单元测试。我不能不使用这个静态类,但显然运行多个测试已经成为问题。所以我的问题是这个。在junit测试中有没有办法重新初始化静态类?那样一次测试不会受到之前测试的影响吗?

I'm trying to unit test a class that references static data from another class. I cannot "not" use this static class, but obviously running multiple tests has become problematic. So my question is this. Is there a way in a junit test to reinitialize a static class? That way one test is not effected by a previous test?

所以换句话说就是这样做的一些方法:

So in other words some way of doing this:

Foo.setBar("Hello");

// Somehow reinitialize Foo

String bar = Foo.getBar(); // Gets default value of bar rather than "Hello"

不幸的是,我无法改变Foo,所以我我坚持使用它。

Unfortunately, I cannot change Foo, so I'm stuck using it.

编辑看来我的例子太简单了。在实际代码中,Bar由系统属性设置,并设置为内部静态变量。所以一旦它开始运行,我就无法改变它。

Edit It appears I made my example a bit too simple. In the real code "Bar" is set by a system property and gets set to an internal static variable. So once it starts running, I can't change it.

推荐答案

虽然它有点脏,我通过使用解决了这个问题反射。我没有重新运行静态初始化程序(这很好),而是采用了脆弱的方法并创建了一个实用程序,可以将字段设置回已知值。以下是我将如何设置静态字段的示例。

Though it was a bit dirty, I resolved this by using reflections. Rather than rerunning the static initializer (which would be nice), I took the fragile approach and created a utility that would set the fields back to known values. Here's a sample on how I would set a static field.

final Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
final Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

field.set(null, value);

这篇关于有没有办法在Java中重新初始化静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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