在Java中创建泛型类型的实例?

可紊 提交于 2020-07-27 10:50:37

问题:

Is it possible to create an instance of a generic type in Java? 是否可以在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: 我根据我所看到的是,答案是思维no因为类型擦除 ),但我有兴趣,如果任何人都可以看到我丢失的东西:

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 . 我将对此开放一会儿,看看是否有人提出与Ian Robertson的Artima Article截然不同的东西


解决方案:

参考一: https://stackoom.com/question/JYV/在Java中创建泛型类型的实例
参考二: https://oldbug.net/q/JYV/Create-instance-of-generic-type-in-Java
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!