Class.cast() vs. cast operator

A co-worker told me Class.cast() is better than cast opertor as it’s safer to handle null reference. Really?

Let’s take a look at the following code snippet. As you can see, basically, there is no difference. Both test cases can pass.

In the function of cast(), it does null and type check but still uses cast operator to cast object.

What’s the difference in byte code? See the source code and byte code (compiled by Java 7) of a simple test case.

Note: Internally, line index starts from 0.

For L1: Instruction of “CHECKCAST” will be invoked to do type casting. In JVM specification, you can find all details about it. Basically, it behaves the same as we expects. See more details here.

For L2: Function cast() will be invoke first and later “CHECKCAST” still needed. Why? I think Java compiler plays a trick. cast() is a generic function, which should return an object in T type. But in runtime, information of type will be erased. So compiler need to put an extra instruction here to do type casting, which should be the same for other generic functions. Actually, in cast(), “CHECKCAST” is not really invoked.

In that case, way to use case() has worse performance.

See a simple performance test.

And the difference is BIG.

Conclusion

I think in most cases, cast operator is safe and simple. But in some cases, when you only have Class object, such as some generic function/class, cast() is also a good choice.