Create new instance of an Array with Java Reflection Method


A new instance of an Array can be 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.

A program that demonstrates the creation of an array using the Array.newInstance() method 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, 5);
      Array.set(arr, 0, 5);
      Array.set(arr, 1, 1);
      Array.set(arr, 2, 9);
      Array.set(arr, 3, 3);
      Array.set(arr, 4, 7);
      System.out.print("The array elements are: ");
      for(int i: arr) {
         System.out.print(i + " ");
      }
   }
}

Output

The array elements are: 5 1 9 3 7

Now let us understand the above program.

A new array instance is created using the Array.newInstance() method. Then the Array.set() method is used to set the values for the array. A code snippet which demonstrates this is as follows −

int arr[] = (int[])Array.newInstance(int.class, 5);
Array.set(arr, 0, 5);
Array.set(arr, 1, 1);
Array.set(arr, 2, 9);
Array.set(arr, 3, 3);
Array.set(arr, 4, 7);

Then the array elements are displayed using the for loop. A code snippet which demonstrates this is as follows −

System.out.print("The array elements are: ");
for(int i: arr) {
   System.out.print(i + " ");
}

Updated on: 25-Jun-2020

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements