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
The sample program that follows modifies the
Field
class's set
methods. To modify the value of a field, perform the following steps: - Create a
Class
object. For more information, see Retrieving Class Objects. - Create a
Field
object by invokinggetField
upon theClass
object. Identifying Class Fields shows you how. - Invoke the appropriate
set
method upon theField
object.
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. 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]
No comments:
Post a Comment