Java: unchecked convert 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 a compiler warning:
Type safety: Unchecked cast from X to Y
I don't understand. Isn't the attempt / capture I made here a check? Can I ignore this warning?
Will my features work as expected? How can I implement it correctly?
I also try to use y to check obj instances, but this doesn't work because of the way Java handles generics
By the way, this function seems very useful to me (making other code cleaner) I wonder if such a function already exists in Java?
An example of how 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(); } }
This often happens in my code I think it's more readable and simple than anything else However, if you have any suggestions on how to make the code simpler, please give me a better suggestion
Solution
So the problem here is that the generic parameter Y used for dynamic conversion is regarded as object It will never throw CCE You threw a CCE in the calling method because you have broken static type security
X makes no sense here:
It is almost certain that the right solution is not to try such a thing It's terrible The spell casting is terrible
However, if you decide 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; } }