我已经结束了构造
List< TaskLocalConstraints> l = new ArrayList< TaskLocalConstraints>(); Class< List< TaskLocalConstraints>> c =(Class< List< TaskLocalConstraints>>)l.getClass();我在想,如果存在类似的话:
Class c = List< TaskLocalConstraints> .class;(我真的不想为了得到它的类型而构造新的对象)
谢谢
解决方案由于所有列表< something> class实际上在运行时对应于同一个类,你可以这样做:
Class< List< TaskLocalConstraints>>> ; c =(Class< List< TaskLocalConstraints>>)List.class;但是由于某种原因,Java并不喜欢它。尝试使用String:
Laj.java:9:不可转换的类型 found:java.lang.Class< java .util.List> required:java.lang.Class< java.util.List< java.lang.String>> Class< List< String>> c =(Class< List< String>>)List.class;好的,让我们来欺骗它:
类<列表与LT;字符串>> c = (Class< List< String>>)(Class<> List.class;这很愚蠢,但是很有效。它产生一个未经检查的警告,但你的例子也是如此。请注意,它不会产生与您的示例相同的类。你的例子返回对象的实际类,即 ArrayList 。这一个显然返回 List 。
Hi is there any way in Java to get staticly generic class type
I have ended up with construct
List<TaskLocalConstraints> l = new ArrayList<TaskLocalConstraints>(); Class<List<TaskLocalConstraints>> c = (Class<List<TaskLocalConstraints>>)l.getClass();I am wondering, if there exists something like:
Class c = List<TaskLocalConstraints>.class;(I really dont want to construct new Object just to get its type)
Thanks
解决方案Since all List<something> classes actually correspond to the same class at runtime, you could do this:
Class<List<TaskLocalConstraints>> c = (Class<List<TaskLocalConstraints>>) List.class;But for some reason, Java doesn't like it. Tried it with String:
Laj.java:9: inconvertible types found : java.lang.Class<java.util.List> required: java.lang.Class<java.util.List<java.lang.String>> Class<List<String>> c = (Class<List<String>>) List.class;Well, let's fool it then:
Class<List<String>> c = (Class<List<String>>) (Class<?>) List.class;It's silly, but it works. It produces an "unchecked" warning, but so does your example. Note that it doesn't result in the same class as your example, though. Your example returns the actual class of the object, namely ArrayList. This one returns List, obviously.
更多推荐
获取泛型类的类型
发布评论