Values of public member fields in a Java object can be obtained (and are usually obtained) with the notation <objectName>.<fieldName>. But Java offers another possibility to do that: using the reflection API it is possible to retrieve a java.lang.reflect.Field object representing a given field and to call specific methods of the Field class to obtain field values. While this process is clearly not necessary in the majority of cases where programmers know a priori the definition of classes they are using in a given program, if such definition is not known (or is only partially known) until when the program is executed the reflection API represents a valuable tool for dealing with unknown classes.

Differently from the usual case where a class definition is available at build time, the fields of a given class accessed through the reflection API can have an arbitrary type, thus the Field class provides a number of methods to retrieve field values of different types; all of these methods take as their unique argument the object from which a field value has to be retrieved. Below are listed the methods that allow retrieving each Java primitive type:

 

·         boolean getBoolean(Object obj)

·         byte getByte(Object obj)

·         char getChar(Object obj)

·         double getDouble(Object obj)

·         float getFloat(Object obj)

·         int getInt(Object obj)

·         long getLong(Object obj)

·         short getShort(Object obj)

 

The following example demonstrates how to retrieve integer field values from an object of the java.awt.Rectangle class. First, a Field object is retrieved for each field of interest by calling the getField(String name) method of the java.lang.Class class, which takes the field name as argument; then, getInt() is called on each Field object to get the int value of the corresponding field.

import java.awt.*;
import java.lang.reflect.*;

public class GetFieldValueExample{
  public static void main(String[] args) throws Exception {
    Rectangle rect = new Rectangle(50, 60);
    Field xField = rect.getClass().getField("x");
    Field yField = rect.getClass().getField("y");
    Field widthField = rect.getClass().getField("width");
    Field heightField = rect.getClass().getField("height");
    System.out.println("x field value: " + xField.getInt(rect));
    System.out.println("y field value: " + yField.getInt(rect));
    System.out.println(
      "width field value: " + widthField.getInt(rect));
    System.out.println(
      "height field value: " + heightField.getInt(rect));
  }
}

The output of this program, reported below, demonstrates that field values are correctly retrieved:

 

 x field value: 0
 y field value: 0
 width field value: 50

 height field value: 60