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