Java: Unchecked cast from X to Y / how to implement castOrNull

强颜欢笑 提交于 2019-12-05 07:06:49

So the problem here is that the generic parameter Y when used for dynamic casting is treated as Object. It will never throw a CCE. You get a CCE thrown in the calling method, as you have broken static type safety.

Also X is entirely pointless here:

Almost certainly the correct solution is not to attempt anything like this. null is bad. Casting is bad.

However, if you are determined to write nonsense, you can pass the Class object:

public static <T> T evilMethod(Class<T> clazz, Object obj) {
    try {
        return clazz.cast(obj);
    } catch (ClassCastException exc) {
        return null;
    }
}
aioobe

I'm not entirely sure it will work as expected. (Depends on what you expect of course :-) but this code will for instance result in a java.lang.ClassCastException (ideone):

public class Main {

    public static void main(String[] args) {
        Integer o = Main.<String, Integer>castOrNull("hello");
    }


    public static <X, Y> Y castOrNull(X obj) {
        try {
            return (Y) obj;
        } catch (ClassCastException e) {
            return null;
        }
    }
}

@Tom Hawtin got the "correct" solution.

You can suppress the warning in this method if you know for sure that it's not a problem by annotating it with @SuppressWarnings("unchecked")

Thanks to the way java generics where designed this code wont work at all. Generics are only useful for compile time type checking as the classes don't use generic type information at runtime.

Your code will be compiled to this:

 static Object castOrNull(Object obj) {
  try {
   return (Object)obj;//FAIL: this wont do anything
  }
  catch(ClassCastException e) {
   return null;
  }
 }

The cast to Object will never fail, and the compiled code has no access to the generic types present at compile time. Since the cast does not happen the way it should you receive a warning for an unchecked operation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!