Manipulating Objects |
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 one of theField
class'sset
methods. To modify the value of a field, perform the following steps:
- Create a
Class
object. For more information, see the section Retrieving Class Objects.- Create a
Field
object by invokinggetField
on theClass
object. The section Identifying Class Fields shows you how.- Invoke the appropriate
set
method on theField
object.The
Field
class provides severalset
methods. Specialized methods, such assetBoolean
andsetInt
, are for modifying primitive types. If the field you want to change is an object invoke theset
method. You can callset
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 aRectangle
object by invoking theset
method. Since thewidth
is a primitive type, anint
, the value passed byset
is anInteger
, which is an object wrapper.The output of the sample program verifies that theimport 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); } } }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]
Manipulating Objects |