Obtain Class from Jackson TypeReference

jackson, java, reflection

Solution

Based on your line of code,

final Type type = typeRef.getType() instanceof ParameterizedType ? ((ParameterizedType)typeRef.getType()).getRawType() : typeRef.getType();

You can safely cast it to a Class like this

final Class clazz = (Class)(typeRef.getType() instanceof ParameterizedType ? ((ParameterizedType)typeRef.getType()).getRawType() : typeRef.getType());

To add a little more explanation -

In the first scenario where ( typeRef is an instance of ParameterizedType), you are retrieving the rawType which would be a Class.

In the second scenario where (typeRef is not an instance of ParameterizedType), it would still be a regular Class because it is not Parameterized.

Problem

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.

Original source