获取泛型类的类型

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

有什么办法在Java中获得静态泛型类类型吗?

我已经结束了构造

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.

更多推荐

获取泛型类的类型

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

发布评论

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

>www.elefans.com

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