Search code examples
javaintrospection

"Cannot be cast to java.lang.Class", namely: which type is not a class


This may seem a dumb question (as it could be very project specific) but in this case it's general enough:

I'm running a piece of code which gives the ClassCastException, with the error message I wrote as title. Here the mentioned cast is from an object of type java.lang.reflect.Type to Class<?>.

Apart from primitive types, which type in Java is not a class?

Thanks for your answers


Solution

  • A Class is a Type but a Type isn't necessary a Class, since Class implements Type.

    Basically, your myType could also be any of the implementing classes of the interfaces GenericArrayType, ParameterizedType, TypeVariable or WildcardType, since they all extend the Type interface.

    Try to print myType.getClass() to see the type you mean: you'll get Class<TheSaidType>.