Create array with Array.newInstance with Java Reflection

Java 8Object Oriented ProgrammingProgramming

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 array with Array.newInstance with Java Reflection −

Example

 Live Demo

import java.lang.reflect.Array;
public class Example {
   public static void main(String[] args) {
      String[] arr = (String[]) Array.newInstance(String.class, 3); // creates a new array
      Array.set(arr, 0, "A");
      Array.set(arr, 1, "B");
      Array.set(arr, 2, "C");
      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 = A
Element 2 = B
Element 3 = C
raja
Published on 09-Jan-2019 08:31:16
Advertisements