Reputation: 1873
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.
Upvotes: 1
Views: 586
Reputation: 28895
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 :)
Upvotes: 3