Is there a form of "type safe" casting in Java?
I can't think of a way in the language itself, but you can easily emulate it like this:
ChildA child = (obj instanceof ChildA ? (ChildA)obj : null);
In java 8 you can also use stream syntax with Optional:
Object o = new Integer(1);
Optional.ofNullable(o)
.filter(Number.class::isInstance)
.map(Number.class::cast)
.ifPresent(n -> System.out.print("o is a number"));
You can use this method which is compatible with all java types :
public static <T> T safeCast(Object o, Class<T> clazz) {
return clazz != null && clazz.isInstance(o) ? clazz.cast(o) : null;
}
Example :
// A given object obj
Integer i = safeCast(obj, Integer.class);