【发布时间】:2020-05-05 23:16:01
【问题描述】:
我在 IntelliJ IDEA 中调试一个方法,在调试模式下我需要设置一个 final 字段的值。有可能以某种方式实现吗?
这是我的 IDE 在调试模式下的图像,我正在尝试更改 collectionId 变量的值。
【问题讨论】:
标签: java debugging intellij-idea
我在 IntelliJ IDEA 中调试一个方法,在调试模式下我需要设置一个 final 字段的值。有可能以某种方式实现吗?
这是我的 IDE 在调试模式下的图像,我正在尝试更改 collectionId 变量的值。
【问题讨论】:
标签: java debugging intellij-idea
嗯,这是可行的。在评估/修改 Intellij 对话框中调整并键入以下内容:
Field finalF = this.getClass().getDeclaredField( "m_field" );
finalF.setAccessible(true);
finalF.setInt(this, newValue);
【讨论】:
IntelliJ IDEA(和 Java 调试器 API)doesn't support it。负责开发者的评论:
Java JDI 代码 (
com.sun.tools.jdi.ObjectReferenceImpl#setValue) 中有一个不允许更改最终字段值的检查,它是很久以前添加的。
ObjectReferenceImpl.java#L236:
// Make sure the field is valid
((ReferenceTypeImpl)referenceType()).validateFieldSet(field);
void validateFieldSet(Field field) {
validateFieldAccess(field);
if (field.isFinal()) {
throw new IllegalArgumentException("Cannot set value of final field");
}
}
不允许这样做的原因是更改 final 字段可能会导致行为不一致:某些值可能已经被编译器“内联”并且不会被更改。
【讨论】: