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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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!

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
unit testing ,reflection ,java ,fields

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}