Java - Reflection Field Accessing

Introduction

You can get or set the value of a field using reflection.

Get the reference of the field, to read the field's value, call the getXxx() method on the field, where Xxx is the data type of the field.

Demo

import java.lang.reflect.Field;

class Person {//w w  w.  j av a2s  .c  o  m
  private int id = -1;
  public String name = "Unknown";

  public Person() {
  }

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

public class Main {
  public static void main(String[] args) {
    Class<Person> ppClass = Person.class;
    try {
      // Create an object of PublicPerson class
      Person p = ppClass.newInstance();

      // Get the reference of name field
      Field name = ppClass.getField("name");

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

      // Set the value of name
      name.set(p, "book2s.com");

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

Result

Related Topics