如何在jdk11中重写静态final字段? [英] How to rewrite a static final field in jdk11?

查看:107
本文介绍了如何在jdk11中重写静态final字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,例如可以在单元测试期间更改static final字段,如下所示:

In the past it was possible to change a static final field eg during a unit test as follows:

static void setFinalStatic(Field field, Object newValue) {
    field.setAccessible(true);

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

    field.set(null, newValue);
  }

致电:

setFinalStatic(MyObject.class.getField("myfield"), "newval");

但是从Java 11(甚至更早)开始,这似乎不再可能(目标字段未更改).

But as of Java 11 (or even before) that seems not to be possible anymore (the target field is not changed).

现在强制进行静态最终字段更改的机会是什么?

What are the chances now of forcing a static final field change?

我知道这是一种黑客.但是在特殊情况下,例如在单个junit测试期间,这是因为不必导入较大的库(如PowerMock).

I know this is kind of a hack. But in special cases, eg during a single junit test, this was the rescue for not having to import larger libraries like PowerMock.

今天还有可能吗?

推荐答案

您应该使用的是PowerMock中的@PrepareForTest.在后台,它使用 javassist ,该工具使用Instrumentation API,使您可以模拟任何内容以前有过.

What you should be using is @PrepareForTest from PowerMock; under the hood it uses javassist, which uses the Instrumentation API that will make it possible for you to mock whatever you had before.

java-12中仅保留了原始的java方法,因为使用modifiers进行的破解将不再起作用.

Only the vanilla java way is gone from java-12, since that hack with modifiers will no longer work.

这篇关于如何在jdk11中重写静态final字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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