在Java中创建泛型类型的实例? [英] Create instance of generic type in Java?

查看:492
本文介绍了在Java中创建泛型类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Java中创建泛型类型的实例?我基于我所看到的答案是 no 由于类型擦除),但我会感兴趣如果任何人都可以看到我缺少的东西:

  class SomeContainer< E> 
{
E createContents()
{
返回什么?


$ / code $编辑:原来,超级类型令牌可以用来解决我的问题,但它需要大量的基于反射的代码,正如下面的一些答案所指出的那样。



我会稍微留下一段时间,看看是否有人想出与Ian Robertson < a href =http://www.artima.com/weblogs/viewpost.jsp?thread=208860 =noreferrer> Artima Article 。

解决方案

你是对的。你不能做新E。但您可以将其更改为

  private static class SomeContainer< E> 
{
E createContents(Class< E> clazz)
{
return clazz.newInstance();
}
}

这很痛苦。但它的工作。用工厂模式包装它使它更容易一些。


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???
    }
}

EDIT: 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.

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.

解决方案

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中创建泛型类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆