Get the Component Type of an Array Object in Java

Java 8Object Oriented ProgrammingProgramming

In order to get the component type of an Array Object in Java, we use the getComponentType() method. The getComponentType() method returns the Class denoting the component type of an array. If the class is not an array class this method returns null.

Declaration − The java.lang.Class.getComponentType() method is declared as follows -

public Class<?> getComponentType()

Let us see a program to the get the component type of an Array Object in Java -

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      int[] array = new int[] {1,2,3};
      // obtain the Class of the component type
      Class arrayClass = array.getClass();
      // obtaining the component type
      Class component = arrayClass.getComponentType();
      if (component != null) {
         System.out.println("Component type is " + component.getName());
      } else {
         System.out.println("Component type is null");
      }
   }
}

Output

Component type is int
raja
Published on 09-Jan-2019 13:10:10
Advertisements