|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
If you are writing a development tool such as a debugger, you must be able to obtain field values. This is a three-step process:The
- Create a
Classobject. The section Retrieving Class Objects shows you how to do this.- Create a
Fieldobject by invokinggetFieldon theClassobject. For more information, see the section Identifying Class Fields.- Invoke one of the
getmethods on theFieldobject.Fieldclass has specialized methods for getting the values of primitive types. For example, the
getIntmethod returns the contents as anintvalue,getFloatreturns afloat, and so forth. If the field stores an object instead of a primitive, then use thegetmethod to retrieve the object.The following sample program demonstrates the three steps listed previously. This program gets the value of the
heightfield from aRectangleobject. Because theheightis a primitive type (int), the object returned by thegetmethod is a wrapper object (Integer).In the sample program, the name of the
heightfield is known at compile time. However, in a development tool such as a GUI builder, the field name might not be known until runtime. To find out what fields belong to a class, you can use the techniques described in the section Identifying Class Fields.Here is the source code for the sample program:
The output of the sample program verifies the value of theimport java.lang.reflect.*; import java.awt.*; class SampleGet { public static void main(String[] args) { Rectangle r = new Rectangle(100, 325); printHeight(r); } static void printHeight(Rectangle r) { Field heightField; Integer heightValue; Class c = r.getClass(); try { heightField = c.getField("height"); heightValue = (Integer) heightField.get(r); System.out.println("Height: " + heightValue.toString()); } catch (NoSuchFieldException e) { System.out.println(e); } catch (SecurityException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } } }heightfield:Height: 325
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.