Create integer array with Array.newInstance in Java


The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method forms a new array with the component type and length as specified in the arguments

Declaration − The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method is declared as follows -

public static Object newInstance(Class<?> componentType, int length) throws IllegalArgumentException, NegativeArraySizeException

Let us see a program to create an integer array with Array.newInstance with Java Reflection -

Example

 Live Demo

import java.lang.reflect.Array;
public class Example {
   public static void main(String[] args) {
      int[] arr = (int[]) Array.newInstance(int.class, 3); // creates a new array
      Array.set(arr, 0, 5);
      Array.set(arr, 1, 9);
      Array.set(arr, 2, 2);
      System.out.println("Element 1 = " + Array.get(arr, 0));
      System.out.println("Element 2 = " + Array.get(arr, 1));
      System.out.println("Element 3 = " + Array.get(arr, 2));
   }
}

Output

Element 1 = 5
Element 2 = 9
Element 3 = 2

Updated on: 25-Jun-2020

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements