在代码中,如果我编写如下代码行:
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.
更多推荐
如何获得泛型参数类型的类实例
发布评论