Reputation: 4721
I have the following code in Java:
public static<T> void doIt(Class<T> t)
{
T[] arr;
arr = (T[])Array.newInstance(t, 4);
}
I want to be able to use doIt using both primitive type such as double and using class objects such as String.
I could do it by using (code compiles):
doIt(double.class);
doIt(String.class);
However, I am worried that in the first case, the Java compiler will actually wrap the double primitive type using a Double class, which I don't want. I actually want it to instantiate a primitive array in this case (while instantiating an objects array with the String case). Does someone know what happens with doIt(double.class)? Is it instantiated as Double or double?
Thanks.
Upvotes: 1
Views: 487
Reputation: 120496
You can create a method that takes an array type instead of the element type and get around the problem that type parameters must be reference types since all array types are reference types.
<T> T doIt(Class<T> arrayType) {
assert arrayType.getElementType() != null;
return <T> Array.newInstance(arrayType.getElementType(), 4);
}
Upvotes: 0
Reputation: 269647
You can make an array of primitive double
like this:
double[] arr = (double[]) Array.newInstance(double.class, 0);
But you can't make this work with generics, because generic parameters are always reference types, not primitive types.
Upvotes: 1
Reputation: 12538
Generics will work with objects so it should be a Double after boxing.
Upvotes: 0
Reputation: 1500135
You couldn't actually make T = double
here - Java generics simply don't work with primitive types. However, you can still instantiate your array:
import java.lang.reflect.*;
public class Test {
public static void main(String[] args) {
createArray(double.class);
}
private static void createArray(Class<?> clazz) {
Object array = Array.newInstance(clazz, 4);
System.out.println(array.getClass() == double[].class); // true
}
}
It really depends on what you want to do with the array afterwards.
Upvotes: 4