Every questions about the java reflection on generic types I found, were asking about getting parameters of a generic type. In my case, I have a ParameterizedType and want to get the Generic container class.
For example, suppose a
ParameterizedTypeImpl.toString()
returns
java.util.List<test.Bar>
Now I want to get a Class of 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. 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?
Is there any better solution than that?
Thank you.
getRawType
should do the trick?
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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.