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.


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.


Java Class文件是由Java Compiler编译源文件之后产生的。Class文件里保存的就是大名鼎鼎的ByteCode(字节码)。其实在JVM Specification有对它格式的详细描述,我也因此用Python写了一个解析器PyJavap。昨天这个小工具也到了第一个Milestone,支持1.5以前的规范。我心里还是很有成就感的,同时对ByteCode也有了更深了理解,在我的GitHub上可以找到。

现在对Java技术的兴趣越来越深,继续研究吧! :smile: