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

4

6

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.

Chayachayote answered 14/10, 2010 at 13:27 Comment(1)
I was thinking about this warning today and whether it was possible to have a checked cast but I don't think that you can do it.South
O
12

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;
    }
}
Organo answered 14/10, 2010 at 13:50 Comment(3)
Thanks. I extended my question to demonstrate where/how I want to use it. Can you please describe why it is a bad thing to do this? And how I can make the code more simple without using such a function?Chayachayote
What about if (clazz.isInstance(obj) instead of catching CCE?Emory
@Tadeusz Kopec You could do. However, you still need to do the cast, either with Class.cast or an unchecked cast. My preference is to not repeat myself and to go for the safe/clear version first. If it matters, you'd probably get better performance in what are probably the error cases (depending upon exact implementation and phase of moon).Organo
U
4

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.

Undersized answered 14/10, 2010 at 13:31 Comment(0)
I
1

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.

Ilona answered 14/10, 2010 at 14:2 Comment(0)
A
0

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")

Acoustician answered 14/10, 2010 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.