1. 在不确定某个參数或对象是否是数组的时候。就能够使用发射机制。把该对象的Class对象传给Array.isArray(Class<?>) 方法进行推断。通过Class对象的 getComponentType() 方法能够进一步知道数组组件的详细类型。数组假设是多维的话能够递归调用Array.isArray;
2.Array.getLength(class)能够得到数组的大小;
3.能够执行时利用反射机制来创建某种类型的数组,利用 java.lang.reflect.Array.newInstance()方法(有两种形式),相同在创建的时候也能够递归的调用该方法。
以下是两个样例
1.利用反射创建,填充,显示数组:
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();
//Sets the value of the indexed component
of the specified
//array object to the specified int value.
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);
}
}
}
2. 数组容量扩容:
public class DoubleArray2
{
public static void main
(String args[]) {
int array[]
= {1, 2, 3, 4, 5};
System. out.println( "Original
size: " + array.length );
System. out.println( "New
size: " + ((int [])doubleArray(array)). length);
System. out.println((( int [])doubleArray(array))[1]);
}
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;
}
}