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 ??
views:
54answers:
2The 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
.
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.