getFields()

  • How to retrieve the fields of a Java class

    The Java reflection API, i.e. the set of classes defined in thejava.lang.reflect package, offers powerful tools to inspect at run-time the definition of any class used in a Java program. The usual starting point to inspect a class definition is acquiring ajava.lang.Class instance representing a given class; it is easy to obtain such an instance because every class defines implicitly a public field calledclass that contains a reference to the Class object representing this class. Among other things,java.lang.Class allows retrieving the definition of all the accessible public fields of a given class: the method to call to do so isgetFields(), which returns an array ofjava.lang.reflect.Field objects representing each of the (class or instance) fields.

    The Field class represents a particular field defined in a class or interface, and contains various methods to get or set the field value, or to get static information such as field name and type. In the following example we will retrieve the name of a field, using thegetName() method. The code first acquires the Class object corresponding to thejava.lang.String class, then retrieves the fields of the String class with a call to getFields(), and finally prints the name of the first field.