Java Reflection array create new array

Introduction

The class Array provides a static method newInstance() to create an array.

The following example creates an array of 5 integers and prints its elements:


import java.lang.reflect.Array;

public class Main {
   public static void main(String args[]) throws Exception {
      int len = 5;
      Object o = Array.newInstance(Integer.class, len);
      for (int i = 0; i < len; i++) {
         Array.set(o, i, new Integer(i));
      }/*  ww w  .  ja va 2 s  . c  o  m*/
      System.out.println(java.util.Arrays.toString((Object[]) o));
   }
}



PreviousNext

Related