Class.cast()
is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class
objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).
It is not similar to reinterpret_cast
, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).
The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>()
with a reference type in Java (remember: Java has runtime type information).
Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).