Previous | Next | Trail Map | Reflection | Manipulating Objects

Setting Field Values

Some debuggers allow users to change field values during a debugging session. If you are writing a tool that has this capability, you must call the one of the Field (in the API reference documentation)class's set methods. To modify the value of a field, perform the following steps:
  1. Create a Class object. For more information, see Retrieving Class Objects.
  2. Create a Field object by invoking getField upon the Class object. Identifying Class Fields shows you how.
  3. Invoke the appropriate set method upon the Field object.

The Field class provides several set methods. Specialized methods, such as setBoolean and setInt, are for modifying primitive types. If the field you want to change is an object, then invoke the set method. You can call set to modify a primitive type, but you must use the appropriate wrapper object for the value parameter.

The sample program that follows modifies the width field of a Rectangle object by invoking the set method. Since the width is a primitive type, an int, the value passed by set is an Integer, which is an object wrapper.

import java.lang.reflect.*;
import java.awt.*;

class SampleSet {

   public static void main(String[] args) {
      Rectangle r = new Rectangle(100, 20);
      System.out.println("original: " + r.toString());
      modifyWidth(r, new Integer(300));
      System.out.println("modified: " + r.toString());
   }

   static void modifyWidth(Rectangle r, Integer widthParam ) {
      Field widthField;
      Integer widthValue;
      Class c = r.getClass();
      try {
        widthField = c.getField("width");
        widthField.set(r, widthParam);
      } catch (NoSuchFieldException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      }
   }
}
The output of the sample program verifies that the width changed from 100 to 300:
original: java.awt.Rectangle[x=0,y=0,width=100,height=20]
modified: java.awt.Rectangle[x=0,y=0,width=300,height=20]


Previous | Next | Trail Map | Reflection | Manipulating Objects