DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • The Cypress Edge: Next-Level Testing Strategies for React Developers

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • How to Convert XLS to XLSX in Java
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How to Change Private Static Final Fields [Snippet]

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.

By 
Sebastian Daschner user avatar
Sebastian Daschner
·
Apr. 18, 17 · Code Snippet
Likes (10)
Comment
Save
Tweet
Share
47.0K Views

Join the DZone community and get the full member experience.

Join For Free

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!

Hack (falconry) Testing

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

Opinions expressed by DZone contributors are their own.

Related

  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • The Cypress Edge: Next-Level Testing Strategies for React Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!