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

编程入门 行业动态 更新时间:2024-10-26 12:28:56
本文介绍了在 Java 中创建泛型类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在 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 中创建泛型类型的实例?

本文发布于:2023-11-02 15:11:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   类型   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!