The Java reflection API, i.e. the set of classes defined in the java.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 a java.lang.Class instance representing a given class; it is easy to obtain such an instance because every class defines implicitly a public field called class 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 is getFields(), which returns an array of java.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 the getName() method. The code first acquires the Class object corresponding to the java.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.

import java.lang.reflect.*;

public class GetFieldsExample {
  public static void main(String[] args){
    Class cls = java.lang.String.class;
    Field field = cls.getFields()[0];
    System.out.println(field.getName());
  }
}

The output of this example program indicates that the first field in the array returned by getFields() for the String class is called CASE_INSENSITIVE_ORDER. Be aware, though, that the order of fields in the returned array is not specified, so in your code you should not rely on any particular order.