• How to find the superclass name by using the getSuperclass() method

    In Java, class hierarchies follow the single inheritance model, i.e. a class can have at most one superclass. The only class that does not have any superclass isjava.lang.Object, while all other classes, including user-defined classes, derive (directly or indirectly) from Object. Thejava.lang.Class class provides a method, called getSuperclass(), to retrieve the direct superclass (i.e. the next class encountered when walking up the hierarchy) of a given class; this method returns a Class object representing the superclass of the Class object on which the method is called; if the method is called on the Object class,null is returned.

  • How to retrieve the component type of an array

    In Java, every array is an object, regardless of whether array elements are objects or primitive types. As a consequence, every array has a corresponding java.lang.Class object, which can be retrieved by calling the getClass() method of java.lang.Object. From the Class object associated to an array, we can retrieve the type of array elements via the getComponentType()method, which returns the Class object representing the element type. Class objects can represent not only classes and interfaces, but also primitive types, so the getComponentType() method works for any array object; if the object on which this method is called does not represent an array, then the method returns null.

    In the following example, we first declare two arrays, and then retrieve their component types and print them on the standard output.