|
|
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 the one of theFieldclass's
setmethods. To modify the value of a field, perform the following steps:
- Create a
Classobject. For more information, see Retrieving Class Objects.- Create a
Fieldobject by invokinggetFieldupon theClassobject. Identifying Class Fields shows you how.- Invoke the appropriate
setmethod upon theFieldobject.The
Fieldclass provides severalsetmethods. Specialized methods, such assetBooleanandsetInt, are for modifying primitive types. If the field you want to change is an object, then invoke thesetmethod. You can callsetto modify a primitive type, but you must use the appropriate wrapper object for the value parameter.The sample program that follows modifies the
widthfield of aRectangleobject by invoking thesetmethod. Since thewidthis a primitive type, anint, the value passed bysetis 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); } } }widthchanged 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 |