Thursday, September 23, 2010

Identifying Class Fields using reflection

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 upon 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 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 upon each of these Field objects.
Here it can be seen that getFields give the fields, getType(), the type of field and getName() gives the name of both type and field...
import java.lang.reflect.*;
import java.awt.*;

class SampleField {

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

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);
The following is a truncated listing of the output generated by the preceding program:
Name: RELATIVE, Type: int Name: REMAINDER, Type: int Name: NONE, Type: int Name: BOTH, Type: int Name: HORIZONTAL, Type: int Name: VERTICAL, Type: int . . .

No comments:

Post a Comment