Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Sep 11, 1998

Array Reflection

The java.lang.reflect package provides an Array class through which the values of an array can be accessed. It is usually more effective to cast the array after it has been obtained through reflection, but there are circumstances where that may not be possible. To access the values of an array through reflection, you must first obtain the array variable field by using the getField() method from the variables owning class. The getField() method returns an object of type java.lang.reflect.Field through which a reference to the member variable can be obtained. To access the values of the array, you can either perform a cast, or use one of the various getter methods in the Array 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();
  }
}
Daniel Savarese
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date