I’m having trouble understanding this bit of code in java.util.Arrays in openjdk. I’m curious why this code uses reflection (Array.newInstance) and why it checks to see if the types are the same? Why can’t it just do T[] copy = (T[]) new Object[newLength] even if the type T and U differ?
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
It can – but then you’d end up with an
Object[]even if you’d asked for aString[]. So this should fail:… but it wouldn’t if
Array.copyOfalways actually returned anObject[].