简体   繁体   中英

Component that checks if objects of one java.lang.reflect.Type can be casted to another?

Java exposes generic type information eg for field types at runtime through interface java.lang.reflect.Type and its subinterfaces (ParameterizedType, WildcardType).

Does anybody know where I can find a component that can determine if objects of one Type can be casted to another Type, eg if a Set<Object> can be casted to Set or a Comparator<User> can be casted to Comparator<? extends Object> Comparator<? extends Object> ?

The solution should work for type information represented by java.lang.reflect.Type , not only Class es, and it should take generics into consideration, ie a List<Integer> should not be castable to a List<Object> .

Regards, Jochen

Guava's TypeToken is designed for exactly this problem, among others. It's meant to be a replacement for Class that's generics-aware. (Disclosure: I contribute to Guava.)

if (clazz.isAssignableFrom(otherClazz))
{
    return true; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM