運用反射類改變數組長度

import java.lang.reflect.Array;

public class ArrayExpand {

public static void main(String[] args) {
	int[] Test = { 1, 2, 3, 4, 5, 6,7 };
	Test = (int[]) expand(Test);
	for (int i = 0; i < Test.length; i++) {
		System.out.println(Test[i]);
	}
}

public static Object expand(Object array) {
	int newLength=1;
	if (array == null) {
		return null;
	}
	Class c = array.getClass();
	if (c.isArray()) {
		int len = Array.getLength(array);// get array length
		if (len >= newLength) {
			return array;
		} else {
			Class cc = c.getComponentType();
			Object newArray = Array.newInstance(cc, newLength);
			System.arraycopy(array, 0, newArray, 0, len);
			return newArray;
		}
	} else {
		System.out.println("is not array");
		throw new ClassCastException("need array");
	}
}
}
相關文章
相關標籤/搜索