Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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 thegetFields
method on aClass
object. ThegetFields
method returns an array ofField
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 theField
objects for the class by callinggetFields
, and then invokes thegetName
andgetType
methods on each of theseField
objects.A truncated listing of the output generated by the preceding program follows: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); } } }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
Feedback Form |
Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.