Create integer array with Array.newInstance in Java

Description

The following code shows how to create integer array with Array.newInstance.

Example


/*from w  w w . jav a  2s. co  m*/
import static java.lang.System.out;

import java.lang.reflect.Array;

public class Main {
  public static void main(String... args) {
    Object o = Array.newInstance(int.class, 0);
    int[] i = (int[]) o;
    int[] j = new int[0];
    out.format("i.length = %d, j.length = %d, args.length = %d%n", i.length,
        j.length, args.length);
    Array.getInt(o, 0); // ArrayIndexOutOfBoundsException
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy