Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Change Private Static Final Fields [Snippet]

DZone's Guide to

How to Change Private Static Final Fields [Snippet]

How do you change what must not be changed?! Well, you don't. Unless you're testing. In which case, this trick will let you change private static fields.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Sometimes you need dirty hacks. This is one that can be useful in testing scenarios — how to change fields that are not meant to be changed.

If we have class Knowledge with the answer for everything:

public class Knowledge {

    private static final Integer ANSWER = 42;

    public String askQuestion(String question) {
        return "The answer to '" + question + "' is: " + ANSWER;
    }
}


We now want to change the answer for testing purposes:

public class KnowledgeTest {

    @Test
    public void testAskQuestion() throws Exception {
        Knowledge knowledge = new Knowledge();

        String answer = knowledge.askQuestion("question?");
        assertThat(answer, is("The answer to 'question?' is: 42"));

        setFinalStaticField(Knowledge.class, "ANSWER", 41);

        answer = knowledge.askQuestion("question?");
        assertThat(answer, is("The answer to 'question?' is: 41"));
    }

    private static void setFinalStaticField(Class<?> clazz, String fieldName, Object value)
            throws ReflectiveOperationException {

        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);

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

        field.set(null, value);
    }
}


We make this possible by setting the field to accessible and removing the final modifier. Then the field can be set using reflection.

Please use this with care and only in test scopes. Also, for primitive types the compiler makes use of constant folding — then such a solution has no effect.

Happy (dirty) hacking!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
unit testing ,reflection ,java ,fields

Published at DZone with permission of Sebastian Daschner, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}