Conduct Array reflection and two dimensional array in Java

Description

The following code shows how to conduct Array reflection and two dimensional array.

Example


/* w ww  . j a  v a 2  s .  c  om*/
import java.lang.reflect.Array;

public class Main {
  public static void main(String... args) {
    Object matrix = Array.newInstance(int.class, 2, 2);
    Object row0 = Array.get(matrix, 0);
    Object row1 = Array.get(matrix, 1);

    Array.setInt(row0, 0, 1);
    Array.setInt(row0, 1, 2);
    Array.setInt(row1, 0, 3);
    Array.setInt(row1, 1, 4);

    for (int i = 0; i < 2; i++)
      for (int j = 0; j < 2; j++)
        System.out.format("matrix[%d][%d] = %d%n", i, j, ((int[][]) matrix)[i][j]);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy