Unchecked casts in Java


How should we handle unchecked casts in Java (search for “unchecked” in the javac documentation)? Here is a brief summary of the kinds of behaviours that this interesting type system “feature” introduces as a consequence of Java’s type-erasure:

Here’s the output:

The last test case, testExplicitCastToIncorrectTypeFailsEarly illustrates the principle of coercing the types via explicit casts at the earliest possible opportunity. This minimizes the scope of the unchecked object: i.e. we try to prevent the unchecked object from “escaping” out into the wild which can lead to ClassCastException being thrown in weird places later on in the code, in what we might describe as “geographically distant” places and places where there is no syntactic cast in the source code.



Content © 2024 Richard Cook. All rights reserved.