Convert from TypeReference<E> to Class<E> without casting (Java)

casting, generics, jackson, java

Solution

You can not cast it: this is very basic Java question -- TypeReference and Class do not derive from same base class so it is against language definition.

But if I guess correctly what you trying to achieve, you can convert raw (type-erased) class by using `JavaType`:

JavaType type = mapper.getTypeFactory().constructType(ref);
Class<?> cls = type.getRawClass();

You can construct `JavaType` out of `TypeReference`, `Class`, or even just basic JDK `Type`.

Problem

I want to go from a `TypeReference<E>` object to a `Class<E>` object in Java, without using casting. I require the usage of `TypeReference` because of the way my code uses Jackson and I need `Class` object because I want to use it to infer a type into one of my other Generic Classes in my app. I know that `TypeReference.getType()` will return a java.lang.reflect.Type object. Basically, if I can find out a way to use code without casting to get from `Type` to `Class`, then I have figured out my problem. Javadoc References: - http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html - http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/type/TypeReference.html

Original source