Java - Reflection Array Reflection

Introduction

You can find out if a Class reference represents an array by using its isArray() method.

java.lang.reflect.Array class can create an array and to manipulate its elements.

Array class getLength() method returns the length value of an array.

To create an array, use the newInstance() static method of the Array class.

The method is overloaded and it has two versions.

Object newInstance(Class<?> componentType, int arrayLength)
Object newInstance(Class<?> componentType, int... dimensions)

To create an array of int of length 5, you would write

int[] ids = (int[])Array.newInstance(int.class, 5);
The above statement is the same as
Object ids = new int[5];

To create an array of int of dimension 5 X 8, you would write

int[][] matrix = (int[][])Array.newInstance(int.class, 5, 8);

The following code illustrates how to create an array dynamically and manipulate its elements.

Demo

import java.lang.reflect.Array;

public class Main {
  public static void main(String[] args) {
    try {//from  w  ww. j  a  v  a 2 s. c  om
      // Create the array of int of length 2
      Object arrayObject = Array.newInstance(int.class, 2);

      // Print the values in array element. Default values will be zero
      int n1 = Array.getInt(arrayObject, 0);
      int n2 = Array.getInt(arrayObject, 1);
      System.out.println("n1 = " + n1 + ", n2=" + n2);

      // Set the values
      Array.set(arrayObject, 0, 101);
      Array.set(arrayObject, 1, 102);

      // Print the values in array element again
      n1 = Array.getInt(arrayObject, 0);
      n2 = Array.getInt(arrayObject, 1);
      System.out.println("n1 = " + n1 + ", n2=" + n2);
    } catch (NegativeArraySizeException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}

Result

Related Topics