• How to retrieve the constructors of a Java class

    In object-oriented programming, a class constructor is a method called every time an object of a given class is created. In Java, a class can have more than one constructor, and different constructors differ in the list of parameters they accept. Thejava.lang.Class<T> class, which contains the definition of an arbitraryT class, offers various methods to inspect a class; one of these methods isgetConstructors(), which returns an array ofjava.lang.reflect.Constructor objects representing each of the public constructors of a given class.

    The constructor class allows retrieving information about a given constructor method, such as its parameters, the type of exceptions it can throw, etc. In the following example we demonstrate how to obtain the name of a constructor for thejava.lang.String class, by using the getName() method of the Constructor class:

  • 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.