Trail: The Reflection API
Lesson: Examining Classes
Identifying Class Fields
Identifying Class Fields
If you are writing an application such as a class browser, you might want to find out what fields belong to a particular class. You can identify a class's fields by invoking the getFields method on a Class object. The getFields method returns an array of Field objects containing one object per accessible public field.

A public field is accessible if it is a member of either:

The methods provided by the Fieldclass allow you to retrieve the field's name, type, and set of modifiers. You can even get and set the value of a field, as described in the sections Getting Field Values and Setting Field Values.

The following program prints the names and types of fields belonging to the GridBagConstraints class. Note that the program first retrieves the Field objects for the class by calling getFields, and then invokes the getName and getType methods on each of these Field objects.

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

class SampleField {

   public static void main(String[] args) {
      GridBagConstraints g = new GridBagConstraints();
      printFieldNames(g);
   }

   static void printFieldNames(Object o) {
      Class c = o.getClass();
      Field[] publicFields = c.getFields();
      for (int i = 0; i < publicFields.length; i++) {
         String fieldName = publicFields[i].getName();
         Class typeClass = publicFields[i].getType();
         String fieldType = typeClass.getName();
         System.out.println("Name: " + fieldName + 
           ", Type: " + fieldType);
         }
      }
}
A truncated listing of the output generated by the preceding program follows:
Name: RELATIVE, Type: int Name: REMAINDER, Type: int Name: NONE, Type: int Name: BOTH, Type: int Name: HORIZONTAL, Type: int Name: VERTICAL, Type: int . . .
Previous page: Examining Interfaces
Next page: Discovering Class Constructors