public static Object goodCopyOf(Object array, int newLength) {
Class<?> cl = array.getClass();
if (!cl.isArray()) return null;
Class<?> componentType = cl.getComponentType();
int length = Array.getLength(array);
Object newArray = Array.newInstance(componentType, newLength);
for (int i = 0; i < Math.min(length, newLength); i++)
Array.set(newArray, i, Array.get(array, i));
return newArray;
}
goodCopyOf 메서드는 Object의 배열뿐만 아니라 어떤 타입의 배열이든 길이를 늘릴 수 있다는 점에 주목하자.
int[ ] primes = { 2, 3, 5, 7, 11 };
primes = (int[ ]) goodCopyOf(primes, 10);
goodCopyOf의 매개변수 타입은 Object[]가 아니라 Object다. int[]는 Object이지만, 객체의 배열은 아니다.