I have a dumb silly question, but sometimes you have to ask them anyways.
I got an Object[] instance in my left hand (it comes from non-generic swing) and a method that accepts a let's say Integer[] as its argument (in my case it's actually a vararg) in my right hand. I'm sure of the content of the array (or I'm ready to pay the price if I'm wrong).
So basically I wrote that :
private static <U, T extends U> T[] cast(final U[] input, final Class<T> newType) {
//noinspection unchecked
final T[] result = (T[]) Array.newInstance(newType, input.length);
System.arraycopy(input, 0, result, 0, input.length);
return result;
}
can you remove the unchecked warning, without unplugging it ?
why haven't Array.newInstance() been genericized ?
why haven't Array.newInstance() been genericized ?
It may be related to generics only being implemented for reference types. Array.newInstance( int.class, 42 ) is perfectly legal, Class<int> is not. With that limitation, there wasn't a backwards compatible way of making it type generic.
The java.util.Arrays class works round this by providing multiple overloads for each primitive type. So this works:
private static <U, T extends U> T[] cast ( final U[] input, final T[] prototype ) {
final T[] result = Arrays.copyOf ( prototype, input.length );
System.arraycopy(input, 0, result, 0, input.length);
return result;
}
If you don't mind passing in an empty array instead of the class object, it avoids the cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With