devxlogo

Array Reflection

Array Reflection

The java.lang.reflect package provides an Array class through whichthe values of an array can be accessed. It is usually more effectiveto cast the array after it has been obtained through reflection, butthere are circumstances where that may not be possible. To access thevalues of an array through reflection, you must first obtain the arrayvariable field by using the getField() method from the variablesowning class. The getField() method returns an object of typejava.lang.reflect.Field through which a reference to the membervariable can be obtained. To access the values of the array, you caneither perform a cast, or use one of the various getter methods in theArray class. The following example demonstrates how to do this:

 import java.lang.reflect.*;public final class ReflectArray {  public int[] intArray;  public ReflectArray() {    intArray = new int[10];    for(int i=0; i < intArray.length; i++)      intArray[i] = i;  }  public static final void main(String[] args) {    ReflectArray reflectArray = new ReflectArray();    Field arrayField;    Object obj;    try {      arrayField = ReflectArray.class.getField("intArray");    } catch(NoSuchFieldException e) {      System.err.println("The intArray field does not exist");      System.exit(1);      return; // This is so compiler can perform proper flow control checking    }    try {      // obj now points to the intArray member of reflectArray      obj = arrayField.get(reflectArray);    } catch(IllegalAccessException e) {      System.err.println("The intArray field is not public");      System.exit(1);      return;    }    if(obj instanceof int[])      System.out.println("obj is an integer array");    // It is more sensible at this point to cast the array, but    // it is possible to access its values through reflection.    int length = Array.getLength(obj);    int value;    // Print the array in reverse order    while(length-- > 0) {      value = Array.getInt(obj, length);      System.out.print(value + " ");    }    System.out.println();  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist