Java - Access private field

Introduction

You need to call a setAccessible(boolean flag) method on a field, method, and constructor reference with a true argument to make that field, method, and constructor accessible to your program.

The following code illustrates how to get access to a private field of the Person class, read its value, and set its new value.

Demo

import java.lang.reflect.Field;

public class Main {
  public static void main(String[] args) {
    Class<Person> personClass = Person.class;
    try {/*from w  w w. ja  v  a2  s .c o  m*/
      // Create an object of the Person class
      Person p = personClass.newInstance();

      // Get the reference to name field
      Field nameField = personClass.getDeclaredField("name");

      // Make the private name field accessible
      nameField.setAccessible(true);

      // Get the current value of name field
      String nameValue = (String) nameField.get(p);
      System.out.println("Current name is " + nameValue);

      // Set a new value for name
      nameField.set(p, "book2s.com");

      // Read the new value of name
      nameValue = (String) nameField.get(p);
      System.out.println("New name is " + nameValue);
    } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
        | IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }
  }
}

class Person {
  private int id = -1;
  private String name = "Unknown";

  public Person() {
  }

  public Person(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String toString() {
    return "Person: id=" + this.id + ", name=" + this.name;
  }
}

Result

Related Topic