如何获得泛型参数类型的类实例

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

在代码中,如果我编写如下代码行:

GClass< Double> x = new GClass< Double>();

让我们说,这个类是这样的:

public static class GClass< T> { private T value = null; public GClass(){ //什么是T? } }

在哪里插入问题什么是T? ,我不希望它的值(即 null ),但它的类型(即 Double )。

解决方案

在执行时您找不到 T ,除非您添加一个构造函数参数,用于取得 Class< T> 参数,并在你的情况下用 Double.class 传递它。您可以随后存储该类并稍后使用它。

这是由于 type erasure ...基本上,泛型只是编译器魔术来插入适当的强制转换,并检查应是否可以。

类型擦除部分的优秀 Java泛型常见问题。

您可能还想阅读Neal Gafter关于超级类型令牌和类型文字。

In code, if I write a code line like this:

GClass<Double> x = new GClass<Double>();

And let say, that the class is like this:

public static class GClass<T> { private T value = null; public GClass() { // What is T? } }

Where I inserted the question "What is T?", I don't want the value (that is null), but its type (that is Double).

解决方案

You can't find out T at execution time unless you add a constructor parameter to take Class<T> parameter and pass call it with Double.class in your case. You can then store that class and use it later.

This is due to type erasure... basically generics are just compiler magic to insert appropriate casts and check that things should be okay.

See the Type Erasure section of the excellent Java Generics FAQ.

You might also want to read Neal Gafter's blog posts about super type tokens and type literals.

更多推荐

如何获得泛型参数类型的类实例

本文发布于:2023-11-02 15:10:59,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   实例   参数   类型

发布评论

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

>www.elefans.com

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