如何在Java中使用MyClass< String> .class`? [英] How to do `MyClass<String>.class` in Java?

查看:260
本文介绍了如何在Java中使用MyClass< String> .class`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何调用 public< T>使用 MyClass< String> .class 作为clazz,在这里我不能实例化或扩展MyClass。 p>

编辑:'David Winslow'和'bmargulies'的回应是正确的(MyClass< String>)doit(MyClass.class); 适用于原始问题,但令人惊讶的是,当方法返回 MyClass< T> 而不是 T 编辑:我已经用MyClass代替了List,并将条件添加到了我原来的问题中。

解决方案

使用 List.class 。因为Java类的类型擦除类型参数完全是一个编译-time构造 - 即使 List< String> .class 是有效的语法,它应该是完全相同的类 List< Date> .class 等等。由于反射在本质上是一种运行时事物,它不能很好地处理类型参数(如在Java中实现的那样)。

如果要使用Class对象(例如)实例化新的List实例,可以将该操作的结果转换为具有适当的类型参数。

 列表< String> list =(List< String>)(ArrayList.class.newInstance()); 


How can call public <T> T doit(Class<T> clazz); using MyClass<String>.class as clazz where I can not instantiate or extend MyClass.

EDIT: 'David Winslow' and 'bmargulies' responses are correct (MyClass<String>) doit(MyClass.class); works for the original question BUT surprisingly when the method returns say MyClass<T> instead of T casting will not compile any more.

Edit: I have replaced List with MyClass and added the condition to my original question.

解决方案

Use List.class. Because of type erasure type parameters to Java classes are entirely a compile-time construct - even if List<String>.class was valid syntax, it would be the exact same class as List<Date>.class, etc. Since reflection is by nature a runtime thing, it doesn't deal well with type parameters (as implemented in Java).

If you want to use the Class object to (for example) instantiate a new List instance, you can cast the result of that operation to have the appropriate type parameter.

List<String> list = (List<String>)(ArrayList.class.newInstance());

这篇关于如何在Java中使用MyClass&lt; String&gt; .class`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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