反射クラスを用いて配列長を変更する
945 ワード
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");
}
}
}