Java type variables

My question is about type variables used in common classes and methods.

Why can't we do something like this T = new T(); or, in other words, why can't we build an object of a type variable?

I know that general information is deleted during compilation, and everything is converted to an Object, so why does the compiler not assume that T is an object, and we will build it?

+6
java generics
source share
2 answers

The problem is that, at run time, the JVM does not know which class actually means T (this information is not stored at run time, which means "type wiping"). Therefore, the JVM just sees that you want to build a new T , but you don’t know which constructor to actually call, so it is not allowed.

There are workarounds, but they will not work as you suggest.

why does the compiler not assume that T is an object and build it ??

Well, of course, the runtime might just create an instance of java.lang.Object for you, but that would not help, since you really wanted T

+9
source share

In addition to sleske's answer; if you need to create T objects inside your general class, the solution must pass the Class<T> reference as an argument to either the constructor or the method that should create new objects, and use this class to create new instances.

+2
source share

All Articles