lundi 16 février 2015

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. 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.






Aucun commentaire:

Enregistrer un commentaire