The Java TM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search

Trail: The Reflection API
Lesson: Examining Classes

## 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:

> - this class
> - a superclass of this class
> - an interface implemented by this class
> - an interface extended from an interface implemented by this class

> The methods provided by the `Field` class 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
>     .
>     .
>     .

| Start of Tutorial > Start of Trail > Start of Lesson | Search