简体   繁体   中英

Java Generic Type Variables

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 ?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM