Use reflection to create, fill, and display an array in Java

Java 8Object Oriented ProgrammingProgramming

An array is created using the java.lang.reflect.Array.newInstance() method. This method basically creates a new array with the required component type as well as length.

The array is filled using the java.lang.reflect.Array.setInt() method. This method sets the required integer value at the index specified for the array.

The array displayed using the for loop. 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[] = (int[])Array.newInstance(int.class, 10);
      int size = Array.getLength(arr);
      for (int i = 0; i<size; i++) {
         Array.setInt(arr, i, i+1);
      }
      System.out.print("The array elements are: ");
      for(int i: (int[]) arr) {
         System.out.print(i + " ");
      }
   }
}

The output of the above program is as follows −

The array elements are: 1 2 3 4 5 6 7 8 9 10

Now let us understand the above program.

The array is created using the Array.newInstance() method. Then a for loop and the Array.setInt() method are used to fill the array. A code snippet which demonstrates this is as follows −

int arr[] = (int[])Array.newInstance(int.class, 10);
int size = Array.getLength(arr);
for (int i=0; i<size; i++) {
   Array.setInt(arr, i, i+1);
}

The array is displayed using a for loop. A code snippet which demonstrates this is as follows −

System.out.print("The array elements are: ");
for(int i: (int[]) arr) {
   System.out.print(i + " ");
}
raja
Published on 09-Jan-2019 10:06:06
Advertisements