问题描述
是否可以在 Java 中创建泛型类型的实例?根据我所看到的,我认为答案是no
(由于类型擦除),但如果有人能看到我的东西,我会很感兴趣我失踪了:
Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no
(due to type erasure), but I'd be interested if anyone can see something I'm missing:
class SomeContainer<E>
{
E createContents()
{
return what???
}
}
结果证明可以使用 Super Type Tokens来解决我的问题,但它需要大量基于反射的代码,如下面的一些答案所示.
It turns out that Super Type Tokens could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.
我将把这个开放一段时间,看看是否有人想出与 Ian Robertson 的 Artima 文章.
I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's Artima Article.
推荐答案
你说得对.你不能做new E()
.但是你可以把它改成
You are correct. You can't do new E()
. But you can change it to
private static class SomeContainer<E> {
E createContents(Class<E> clazz) {
return clazz.newInstance();
}
}
很痛苦.但它有效.将其包装在工厂模式中使其更容易接受.
It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.
这篇关于在 Java 中创建泛型类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!