Generics in Java - Creating an Instance of T

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 a primitive type, such as double, and using class objects such as String.

I could do this using (code compilation):

  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 the Double class, which I don't want. I really want it to create a primitive array in this case (when creating an instance of an array of objects with a String case). Does anyone know what happens with doIt (double.class)? Is this an instance of Double or double?

Thanks.

+1
source share
4 answers

You could not do T = double here - Java generics just 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.

+4
source

You can make an array of primitive double as follows:

 double[] arr = (double[]) Array.newInstance(double.class, 0); 

But you cannot do this work with generics, because generic parameters are always reference types, not primitive types.

+1
source

Generics will work with objects, so it should be double after boxing.

0
source

You can create a method that will use an array type instead of an element type and work around the problem, the type parameters must be reference types, since all types of arrays are reference types.

 <T> T doIt(Class<T> arrayType) { assert arrayType.getElementType() != null; return <T> Array.newInstance(arrayType.getElementType(), 4); } 
0
source

Source: https://habr.com/ru/post/915058/


All Articles