Previous | Next | Trail Map | The Reflection API | Manipulating Objects

Getting Field Values

If you are writing a development tool like a debugger, you must be able to obtain field values. This is a three-step process:
  1. Create a Class object. Retrieving Class Objects shows you how to do this.
  2. Create a Field object by invoking getField upon the Class object. For more information, see Identifying Class Fields.
  3. Invoke one of the get methods upon the Field object.
The Field (in the API reference documentation)class has specialized methods for getting the values of primitive types. For example, the getInt method returns the contents as an int value, getFloat returns a float, and so forth. If an object is stored in the field instead of a primitive, then use the get method to retrieve the object.

The following sample program demonstrates the three steps listed previously. This program gets the value of the height field from a Rectangle object. Because the height is a primitive type (int), the object returned by the get method is a wrapper object (Integer).

In the sample program, the name of the height field is known at compile time. However, in a development tool like a GUI builder, the field name might not be known until run time. To find out what fields belong to a class, you can use the techniques described in Identifying Class Fields.

Here is the source code for the sample program:

import 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);
      }
   }
}
The output of the sample program verifies the value of the height field:
Height: 325


Previous | Next | Trail Map | The Reflection API | Manipulating Objects