Set the value of a final field in debug mode in IntelliJ IDEA

Viewed 1430

I'm debugging a method in IntelliJ IDEA and in debug mode I need to set the value of a final field. Is possible to achieve in some way?

This is the image of my IDE in debug mode, I'm trying to change the value of the collectionId variable.

IDE

2 Answers

IntelliJ IDEA (and Java debugger API) doesn't support it. Comment from the responsible developer:

There's a check in Java JDI code (com.sun.tools.jdi.ObjectReferenceImpl#setValue) that does not allow to change value of a final field, it was added long ago.

ObjectReferenceImpl.java#L236:

        // Make sure the field is valid
        ((ReferenceTypeImpl)referenceType()).validateFieldSet(field);

ReferenceTypeImpl.java#L614:

    void validateFieldSet(Field field) {
        validateFieldAccess(field);
        if (field.isFinal()) {
            throw new IllegalArgumentException("Cannot set value of final field");
        }
    }

The reason why it's not allowed is that changing final fields may lead to inconsistency in behavior: some values may be "inlined" by the compiler already and will not be changed.

Well, it is doable. Adapt & type the below in the evaluate/modify Intellij dialog:

Field finalF = this.getClass().getDeclaredField( "m_field" );
finalF.setAccessible(true);
finalF.setInt(this, newValue);
Related