在Java中创建泛型类型的实例?是否可以在Java中创建泛型类型的实例?我的想法是基于我所看到的答案no (由于类型擦除),但如果有人能看到我缺少的东西,我会感兴趣的:class SomeContainer<E>{
E createContents()
{
return what???
}}编辑:原来超级代币可以用来解决我的问题,但它需要大量基于反射的代码,如下所示。我暂时不谈这个问题,看看有没有人能拿出和伊恩·罗伯逊截然不同的东西Artima条款.
4 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
public abstract class Foo<E> {
public E instance;
public Foo() throws Exception {
instance = ((Class)((ParameterizedType)this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
...
}}// notice that this in anonymous subclass of Fooassert( new Foo<Bar>() {}.instance instanceof Bar );
收到一只叮咚
TA贡献1821条经验 获得超5个赞
interface Factory<E> {
E create();}class SomeContainer<E> {
private final Factory<E> factory;
SomeContainer(Factory<E> factory) {
this.factory = factory;
}
E createContents() {
return factory.create();
}}添加回答
举报
0/150
提交
取消
