Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 936865
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T21:22:53+00:00 2026-05-15T21:22:53+00:00

I want to set the value of a private field using reflection for unit

  • 0

I want to set the value of a private field using reflection for unit testing.

Problem is, that field is static.

Here’s what I’m working from:

/**
   * Use to set the value of a field you don't have access to, using reflection, for unit testing.
   * 
   * Returns true/false for success/failure.
   * 
   * @param p_instance an object to set a private field on
   * @param p_fieldName the name of the field to set
   * @param p_fieldValue the value to set the field to
   * @return true/false for success/failure
   */
  public static boolean setPrivateField(final Object p_instance, final String p_fieldName, final Object p_fieldValue) {
    if (null == p_instance)
      throw new NullPointerException("p_instance can't be null!");
    if (null == p_fieldName)
      throw new NullPointerException("p_fieldName can't be null!");

    boolean result = true;

    Class<?> klass = p_instance.getClass();

    Field field = null;
    try {
      field = klass.getDeclaredField(p_fieldName);

      field.setAccessible(true);
      field.set(p_instance, p_fieldValue);

    } catch (SecurityException e) {
      result = false;
    } catch (NoSuchFieldException e) {
      result = false;
    } catch (IllegalArgumentException e) {
      result = false;
    } catch (IllegalAccessException e) {
      result = false;
    }

    return result;
  }

I realize this has probably already been answered on SO, but my search didn’t turn it up…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T21:22:54+00:00Added an answer on May 15, 2026 at 9:22 pm

    Basically the problem is your utility method, which assumes you have an instance. It’s reasonably easy to set a private static field – it’s exactly the same procedure as for an instance field, except you specify null as the instance. Unfortunately your utility method uses the instance to get the class, and requires it to be non-null…

    I’d echo Tom’s caveat: don’t do that. If this is a class you have under your control, I’d create a package level method:

    void setFooForTesting(Bar newValue)
    {
        foo = newValue;
    }
    

    However, here’s a complete sample if you really, really want to set it with reflection:

    import java.lang.reflect.*;
    
    class FieldContainer
    {
        private static String woot;
    
        public static void showWoot()
        {
            System.out.println(woot);
        }
    }
    
    public class Test
    {
        // Declared to throw Exception just for the sake of brevity here
        public static void main(String[] args) throws Exception
        {
            Field field = FieldContainer.class.getDeclaredField("woot");
            field.setAccessible(true);
            field.set(null, "New value");
            FieldContainer.showWoot();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

my problem is that, i want to save class object java.lang.reflect.Field into database using
i want to set the default value in a sql server 2005 datetime field
I've got a set of static enumeration classes that I'm using to hold meaningful
Goal: Display Encapsulate field from Player Problem: Want to display datamember_id , _name and
I want to set my GtkComboBox to have some default value/name, on it as
I have a textbox whose value I want to set based on the inner
I have a site collection and I want to set the search center value
I don't want to give an initial value. I want to set these later
.NET I want to clone a value type's fields. How can i set a
I want to return a set of values from function till the point they

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.