开发者

Java Generic Type Variables

开发者 https://www.devze.com 2023-01-21 05:01 出处:网络
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 cons开发者_StackOverflow中文版truct an obje

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 cons开发者_StackOverflow中文版truct 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号