Java-Programming-Docs Help

Array Reflection

If for some reason you are ever unsure whether an argument or object is an array, you can retrieve the object's Class object and ask it. The isArray() method of the Class class will tell you. Once you know you have an array, you can ask the getComponentType() method of Class what type of array you actually have. The getComponentType() method returns null if the isArray() method returns false. Otherwise, the Class type of the element is returned. You can recursively call isArray() if the array is multidimensional. It will still have only one component type. In addition, you can use the getLength() method of the Array class found in the java.lang.reflect package to discover the length of the array.

To demonstrate, code below shows that the argument to the main() method is an array of java.lang.String objects where the length is the number of command−line arguments specified:

If you don't use the isArray() and getComponentType() methods and you try to print the Class type for an array, you'll get a string that includes a [ followed by a letter and the class name (or no class name if a primitive). For instance, if you tried to print out the type variable in the printType() method above, you would get class [Ljava.lang.String; as the output

In addition to asking an object if it is an array and what type of array it is, you can also create arrays at runtime with the java.lang.reflect.Array class. This might be helpful to create generic utility routines that perform array tasks such as size doubling.

To create a new array, use the newInstance() method of Array, which comes in two varieties. For single dimension arrays you would normally use the simpler version, which acts like the statement new type[length] and returns the array as an object:

public static Object newInstance(Class type, int length);

For example, the following code creates an array with room for five integers:

int[] array = (int[]) java.lang.reflect.Array.newInstance(int.class, 5);

The second variety of the newInstance() method requires the dimensions to be specified as an array of integers:

public static Object newInstance(Class type, int[] dimensions);

In the simplest case of creating a single dimension array, you would create array with only one element. In other words, if you were to create the same array of five integers, instead of passing the integer value of 5, you would need to create an array of the single element 5 to pass along to the newInstance() method:

int[] dimensions = {5}; int[] array = (int[]) java.lang.reflect.Array.newInstance(int.class, dimensions);

As long as you only need to create rectangular arrays, you can fill up the dimensions array with each array length. For example, the following is the equivalent of creating a 3 × 4 array of integers:

int[] dimensions = {3, 4}; int[][] array = (int[][]) java.lang.reflect.Array.newInstance(int.class, dimensions);
    Last modified: 16 July 2024