Search code examples
javacastinginstanceofclasscastexception

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


I have implemented this function:

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

This gives me the compiler warning:

Type safety: Unchecked cast from X to Y

Which I don't exactly understand. Isn't the try/catch which I am doing here a check for it? Can I ignore the warning?

Will my function work as expected or not? How would I implement it correctly?

I also tried with a obj instanceof Y check but that doesn't work because of the way Java handle generics.

Btw., this function seems quite useful to me (to make some other code more clean). I wonder if such a function may already exist in Java?


One example where I want to use it:

    void removeEmptyRawStrings() {
        for(Iterator<Entity> e = entities.iterator(); e.hasNext();) {
            RawString s = castOrNull(e.next());
            if(s != null && s.content.isEmpty()) e.remove();
        }
    }

I have cases like these quite often in my code. And I think this is more readable and simpler than anything else. But please give me a better suggestion if you have any about how to make that code even more simple.


Solution

  • 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;
        }
    }