如何获得泛型参数类型的类实例 [英] How to obtain class instance of generic argument type

查看:107
本文介绍了如何获得泛型参数类型的类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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.

这篇关于如何获得泛型参数类型的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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