Convert java.lang.reflect.Type to Class clazz

前端 未结 6 1815
闹比i
闹比i 2021-02-12 11:43

How can I convert java.lang.reflect.Type to Class clazz?

If I have one method as next which has an argument of Class

6条回答
  •  我在风中等你
    2021-02-12 12:09

    It would be weird that a Type would be anything else than a Class... Javadoc for Type says

    All Known Implementing Classes: Class

    So unless you have special libraries that use non Class Types, you can simply cast - but you must be ready for a possible ClassCastException. Beware: Java use undocumented Type implementation to represent generics, see below.

    You can explicitely process it or not because it is an unchecked exception:

    Explicit way:

    try {
        Class clazz = (Class) type;
    }
    catch (ClassCastException ex) {
        // process exception
    }
    

    Implicit way:

    Class clazz = (Class) type;
    

    but the current method could throw...


    EDIT per @Andy Turner's comment:

    Beware: Type type = new ArrayList().getClass().getGenericSuperclass(); yields something that's a Type but not a Class. This one is a ParameterizedType, so you can use getRawType() method to find the actual class, but others might exist.

提交回复
热议问题