jeudi 19 février 2015

Obtain Class from Jackson TypeReference

I have some code which needs to unpick a Jackson TypeReference to find out if it is a Collection. At the moment the best I can come up with is:



// Sample type reference - in reality this is an argument to the method
final TypeReference<List<String>> typeRef = new TypeReference<List<String>>(){};

// Obtain the Java reflection type from the TypeReference
final Type type = typeRef.getType() instanceof ParameterizedType ? ((ParameterizedType)typeRef.getType()).getRawType() : typeRef.getType();

// Obtain the name of the class (or interface)
final String typeName = type.toString().replace("class ", "").replace("interface ", "");

// And find out if it is a Collection
final boolean isCollection = Collection.class.isAssignableFrom(Class.forName(typeName));


But I would hope that there is a way to do this without string manipulation. Is there a better way to go from the Java Type to the Class, or indeed to check assignability directly from either the TypeReference or the Type?


This needs to work on Android so any features added in Java 8 can't be used.






Aucun commentaire:

Enregistrer un commentaire