Using reflection to check array type and length in Java

Java 8Object Oriented ProgrammingProgramming

The array type can be checked using the java.lang.Class.getComponentType() method. This method returns the class that represents the component type of the array. The array length can be obtained in int form using the method java.lang.reflect.Array.getLength().

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.lang.reflect.Array;
public class Demo {
   public static void main (String args[]) {
      int[] arr = {6, 1, 9, 3, 7};
      Class c = arr.getClass();
      if (c.isArray()) {
         Class arrayType = c.getComponentType();
         System.out.println("The array is of type: " + arrayType);
         System.out.println("The length of the array is: " + Array.getLength(arr));
         System.out.print("The array elements are: ");
         for(int i: arr) {
            System.out.print(i + " ");
         }
      }
   }
}

Output

The array is of type: int
The length of the array is: 5
The array elements are: 6 1 9 3 7

Now let us understand the above program.

First the array arr is defined and the getClass() method is used to get the runtime class of arr. A code snippet which demonstrates this is as follows −

int[] arr = {6, 1, 9, 3, 7};
Class c = arr.getClass();

Then the array type is obtained using getComponentType() method. The length of the array is obtained using the Array.getLength() method. Finally, the array is displayed. A code snippet which demonstrates this is as follows −

if (c.isArray()) {
   Class arrayType = c.getComponentType();
   System.out.println("The array is of type: " + arrayType);
   System.out.println("The length of the array is: " + Array.getLength(arr));
   System.out.print("The array elements are: ");
   for(int i: arr) {
      System.out.print(i + " ");
   }
}
raja
Published on 09-Jan-2019 12:04:27
Advertisements