isArray() //判断是否是一个数组
getComponentType() //判断数组元素的类型
Array.getLength(class clazz) //获得clazz的长度
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));
}
}
}
在运行时创建数组
//创建一个类型为int的,长度为5的数组
int array[] = (int[])Array.newInstance(int.class, 5);
运行时数组的get和set
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)
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);
}
}
}