Java Generic Type Variables

generics, java

Solution

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`.

Problem

My question is about type variables used in generic classes and methods. Why can't we do something like this `T = new T();` or in other words, why can't we 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 ?

Original source