|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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 theFieldclass's
setmethods. To modify the value of a field, perform the following steps:
- Create a
Classobject. For more information, see the section Retrieving Class Objects.- Create a
Fieldobject by invokinggetFieldon theClassobject. The section Identifying Class Fields shows you how.- Invoke the appropriate
setmethod on theFieldobject.The
Fieldclass provides severalsetmethods. Specialized methods, such assetBooleanandsetInt, are for modifying primitive types. If the field you want to change is an object 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]
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.