MyType myType = someObj.getMyTypeObject(); if (myType instanceof MyDerivedType) { MyDerivedType myDerivedType = (MyDerivedType) myType; }
Did you ever need to write something like this? I think it might be common approach (when using some loose typing containers) to deal with objects that returns base type instead of derived type that we need. It is also obfuscated with defensive programming structure (by using instanceof type check). I don’t like defensive programming, where it is not needed so in my case it would turn into:
MyDerivedType myDerivedType = (MyDerivedType) someObj.getMyTypeObject();
You must admit that both these constructs looks awful (and sometimes requires to suppress compilers warnings). Most of the times this can be solved by redesigning corresponding objects, that casting is not needed, but sometimes you have to end up with one of these. Continue reading