tags:

views:

54

answers:

2

Hello,
my question is about type variables used in generic classes and methods,
why can't we do something like this T = new T(); "Construct an object of the type variable"
i know that generic information is erased during compilation, and everything is converted to
Object, so why doesn't the compiler assume that T is an object and let us construct it ??

+4  A: 

The problem is that at runtime the JVM does not know which class the T actually stands for (that information is not retained at runtime, that's what "type erasure" means). Therefore the JVM just sees that you want to construct a new T, but has no idea which constructor to actually invoke - hence it's not allowed.

There are workarounds, but it will not work as you propose.

why doesn't the compiler assume that T is an object and let us construct it ??

Well, of course the runtime could just construct an instance of java.lang.Object for you, but that would not really help, as you really wanted a T.

sleske
one thing, does the runtime see T or Object, isn't the generic information erased, ??
Ebraheem Najjar
I don't know what the runtime "sees", as I don't know how this is implemented internally. I believe it just does not see any type at all. It can probably distinguish between cases where there is really "Object" written in the code, and cases where a type was erased.
sleske
It just sees an `Object`.
pelotom
+1  A: 

In addition to sleske's answer; if you need to create objects of T inside your generic class, the solution is to pass a Class<T> reference as argument to either the constructor or the method that needs to create new objects and use that class to create new instances.

rsp
or pass in a Factory<T>?
Ishtar
Yes, that's what I meant by "there are workarounds". Thanks for adding it :-).
sleske
I don't condone this approach, but if you like to write really hacky code, you can still work around it using reflection. `((ParametrizedType)getClass()).getActualTypeArguments()[0].createNewInstance()`. This assumes a default constructor of course.
Joeri Hendrickx