为什么不能使用“new”创建泛型类型的实例?运营商? [英] Why can't you create an instance of a generic type using "new" operator?
问题描述
我发现很多关于如何克服此限制的帖子,但没有关于为何存在此限制的帖子(除了这个,刚才提到它与类型擦除有关。)
I found a lot of posts about how to overcome this limitation, but none about why this limitation exists (except this one, which just mentions it has to do with type erasure).
那么为什么你不能创建泛型类型的实例吗?
So why can't you create an instance of a generic type?
为了澄清,我的问题不是如何它可以完成。我知道在C#中它是可能的,为什么不用Java呢?我很好奇为什么Java人员没有实现类似的机制?为什么迫使Java开发人员使用可能导致运行时错误的尴尬变通方法?这种机制是否存在潜在危害?
To clarify, my question is not how it can be done. I know it's possible in C#, so why not in Java? I'm curious about why the Java folks did not implement a similar mechanism? Why force Java developers to use awkward workarounds that have the potential to result in a runtime error? Are there any potential hazards from such a mechanism?
推荐答案
简答:
Java是编译的编程语言,这意味着您的字节码在运行时是常量。如果 E
未知,则无法为 new E()
生成字节码。
Short answer:
Java is a compiled programming language, which means that your bytecode is constant at runtime. It is impossible to generate bytecode for new E()
if E
is unknown.
解释:通用信息是在运行时擦除:
public class Container<E> {
private E item;
public E getItem() {return item;}
}
class BoxWithPresent extends Container<Present> {
}
class SimpleBox extends Container {
}
In字节码类 BoxWithPresent
包含类型 Present
的字段 item
,但是class SimpleBox
包含对象
类型的字段 item
(因为类型未指定 E
。
In bytecode class BoxWithPresent
contains field item
of type Present
, but class SimpleBox
contains field item
of type Object
(because type E
was not specified).
现在编写抽象实例化方法:
Now you write abstract instantiation method:
public class Container<E> {
public <E> E createE() {
return new E(); // imagine if that was allowed
}
}
应该使用什么字节码在这里生成? .class
文件现在是在编译时生成的,但我们不知道什么是 E
类型。
What bytecode should be generated here? .class
file is generated right now, at compilation time, but we have no idea what is E
type.
所以..可以新的T()
替换为 new Object()
?坏主意,类 BoxWithPresent
不喜欢它,因为它希望 E
是目前
。
So.. can new T()
be replaced with new Object()
? Bad idea, class BoxWithPresent
won't like it, because it expects that E
is Present
.
是否可以用 class.newInstance()
替换?再说不,方法范围内没有 class
变量。
Can it be replaced with class.newInstance()
? Again no, there is no class
variable in method scope.
这就是为什么 new E ()
是不可能的。
但是将 class
作为参数传递,或者提取通用信息。
That's why new E()
is impossible.
But there are workarounds with passing class
as parameter, or extracting generic information.
这篇关于为什么不能使用“new”创建泛型类型的实例?运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!