简体   繁体   English

如何在Java中获取ParameterizedType的通用容器类

[英]How to get generic container class of a ParameterizedType in java

Every questions about the java reflection on generic types I found, were asking about getting parameters of a generic type. 我发现的有关泛型类型的java反射的每个问题都在询问获取泛型类型的参数。 In my case, I have a ParameterizedType and want to get the Generic container class. 就我而言,我有一个ParameterizedType并想获取Generic容器类。

For example, suppose a 例如,假设

ParameterizedTypeImpl.toString()

returns 回报

java.util.List<test.Bar>

Now I want to get a Class of java.util.List. 现在,我想获取一个java.util.List类。

It might sound a little wired for you, but I need you to suppose it is what it is! 听起来对您来说有点有线,但是我需要您假设它就是它!

So what I need is something like 所以我需要的是

 Class cls = ((MagicCast)ParameterizedTypeImpl.mayBeAMagicHere()).someOtherMagic();
 //Now cls is of type List

The only way I can think of is to use subString or regex to get java.util.List out of the ParameterizedTypeImpl.toString() and then use class.forName to get the class. 我能想到的唯一方法是使用subString或regex从ParameterizedTypeImpl.toString()中获取java.util.List,然后使用class.forName获取该类。 But I don't know how portable it is. 但是我不知道它有多便携。 Is it possible some versions of java have other implementation for the toString of a ParameterizedTypeImpl? Java的某些版本是否可能对ParameterizedTypeImpl的toString具有其他实现?

Is there any better solution than that? 有没有比这更好的解决方案了?

Thank you. 谢谢。

getRawType should do the trick? getRawType应该做的把戏吗?

Class<?> theClass = (Class<?>) yourParameterizedType.getRawType();

The cast should be safe since the docs say that the returned value is the Type object representing the class or interface that declared this type , but well, no guarantees guaranteed :) 强制转换应该是安全的,因为文档说返回的值是表示声明此类型的类或接口的Type对象 ,但是,不能保证:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM