From: http://www.ibm.com/developerworks/cn/java/j-arrays/#3
Array reflection
If, for some reason, you are not sure whether the parameter or object is an array, you can retrieveClass
Object and ask it.Class
ClassisArray()
The method will tell you. Once you know that you have an array, you can askClass
OfgetComponentType()
Method. What type of array do you actually have. IfisArray()
The method returns false.getComponentType()
Method return is null. Otherwise, the class type of the element is returned. If the array is multidimensional, you can callisArray()
. It will still contain only one component type. In addition, you can usejava.lang.reflect
Found in the packageArray
ClassgetLength()
Method to obtain the length of the array.
For demonstration, listing 2-3 showsmain()
The method parameter isjava.lang.String
Object array. The length of the array is determined by the number of command line parameters:
Listing 2-3. Use reflection to check the array type and length
public class ArrayReflection { public static void main (String args[]) { printType(args); } private static void printType (Object object) { Class type = object.getClass(); if (type.isArray()) { Class elementType = type.getComponentType(); System.out.println("Array of: " + elementType); System.out.println(" Length: " + Array.getLength(object)); } }} |
Note:IfprintType()
Used forbuttons
Andcomponents
Variable call, each of which indicates that the array isjava.awt.Button
Type.
If you do not useisArray()
AndgetComponentType()
Method, and try to print the class type of the array, you will get a string containing [, followed by a letter and class name (if it is a basic data type, there is no class name. For exampleprintType()
Type variable in the method, you will getclass [Ljava.lang.String;
As output.
In addition to querying whether an object is an array or what type of array, you can also usejava.lang.reflect.Array class
Create an array. This is useful for creating common Utility Routines that execute array tasks, such as doubling the size. (We will return to that point immediately .)
To create a new array, useArray
OfnewInstance()
Method, which has two forms of change. For a one-dimensional array, you usually use a relatively simple version. Its execution method is as follows:new type [length]
And return an array as an object:public static Object newInstance(Class type, int length)
. For example, the following code creates an array of five integer space sizes:
int array[] = (int[])Array.newInstance(int.class, 5); |
Note:To specify the basic data typeClass
Object. You only need to add. class at the end of the basic data type name. You can also use the type variable in the packaging class, such as integer. type.
newInstance()
The second form of change in the method requires that the dimension be specified as an integer array:public static Object newInstance(Class type,int dimensions [])
. In the simplest case of creating a one-dimensional array, you will create an array with only one element. In other words, if you want to create the same array containing five integers, you need to create an array with a single element 5 and pass itnewInstance()
Instead of passing the integer 5.
int dimensions[] = {5};int array[] = (int[])Array.newInstance(int.class, dimensions); |
When you only need to create a rectangle array, you can fill in the length of each array to this dimensions array. For example, the following code is equivalent to creating a 3x4 integer array.
int dimensions[] = {3, 4};int array[][] = (int[][])Array.newInstance(int.class, dimensions); |
However, if you want to create a non-rectangular array, you need to callnewInstance()
Method. The first call will define the length of the external array and get a seemingly odd class parameter ([]. Class applies to elements that arefloat
Type array ). Each subsequent call defines the length of each internal array. For example, the following shows how to create an elementfloat
The size of the internal array is set to a group of Ballon bottles: one element in the first row, two in the second row, three in the third row, and four in the fourth row. To help you visualize this situation, let's review the Triangle Array shown in Figure 2-4 earlier.
float bowling[][] = (float[][])Array.newInstance(float[].class, 4);for (int i=0; i<4; i++) { bowling[i] = (float[])Array.newInstance(float.class, i+1);} |
Once an array is created at run time, you can also obtain and set array elements. This is usually not done unless the square brackets on the keyboard fail or you work in a dynamic programming environment (the group name is unknown when the program is created. As shown in Table 2-2,Array
Class has a series of getter and setter methods used to obtain and set array elements. The method to use depends on the array type you are processing.
Table 2-2. array getter and setter Methods
Getter Method |
Setter Method |
Get (Object array, int index) |
Set (Object array, int index, object value) |
Getboolean (Object array, int index) |
Setboolean (Object array, int index, Boolean value) |
Getbyte (Object array, int index) |
Setbyte (Object array, int index, byte value) |
Getchar (Object array, int index) |
Setchar (Object array, int index, char value) |
Getdouble (Object array, int index) |
Setdouble (Object array, int index, double value) |
Getfloat (Object array, int index) |
Setfloat (Object array, int index, float value) |
Getint (Object array, int index) |
Setint (Object array, int index, int value) |
Getlong (Object array, int index) |
Setlong (Object array, int index, long value) |
Getshort (Object array, int index) |
Setshort (Object array, int index, short value) |
Note:You can always useget()
Andset()
Method. If the array is an array of basic data types,get()
Method return value orset()
The value parameter of the method will be packaged into the packaging class for the basic data type, likeint
ArrayInteger
Class.
Listing 2-4 provides a complete example of how to create, populate, and display array information. Square brackets are only available inmain()
Method declaration.
Listing 2-4. Using Reflection to create, populate, and display Arrays
import java.lang.reflect.Array;import java.util.Random;public class ArrayCreate { public static void main (String args[]) { Object array = Array.newInstance(int.class, 3); printType(array); fillArray(array); displayArray(array); } private static void printType (Object object) { Class type = object.getClass(); if (type.isArray()) { Class elementType = type.getComponentType(); System.out.println("Array of: " + elementType); System.out.println("Array size: " + Array.getLength(object)); } } private static void fillArray(Object array) { int length = Array.getLength(array); Random generator = new Random(System.currentTimeMillis()); for (int i=0; i<length; i++) { int random = generator.nextInt(); Array.setInt(array, i, random); } } private static void displayArray(Object array) { int length = Array.getLength(array); for (int i=0; i<length; i++) { int value = Array.getInt(array, i); System.out.println("Position: " + i +", value: " + value); } }} |
During running, the output will be as follows (although the random number is different ):
Array of: intArray size: 3Position: 0, value: -54541791Position: 1, value: -972349058Position: 2, value: 1224789416 |
Let's return to the previous example and create a method to double the array size. Since you know how to obtain the array type, you can create a method to double the size of any type of array. This method ensures that we can get an array before getting its length and type. Then, before copying the original group of elements, it doubles the size of the new array.
static Object doubleArray(Object original) { Object returnValue = null; Class type = original.getClass(); if (type.isArray()) { int length = Array.getLength(original); Class elementType = type.getComponentType(); returnValue = Array.newInstance(elementType, length*2); System.arraycopy(original, 0, returnValue, 0, length); } return returnValue;} |