There is absolutely no reason to write Foo.class.cast(o)
, it is equivalent to (Foo)o
.
In general, if X
is a reifiable type, and Class<X> clazz
, then clazz.cast(o)
is same as (X)o
.
If all types are reifiable, method Class.cast()
is therefore redundant and useless.
Unfortunately, due to erasure in current version of Java, not all types are reifiable. For example, type variables are not reifiable.
If T
is a type variable, cast (T)o
is unchecked, because at runtime, the exact type of T
is unknown to JVM, JVM cannot test if o
is really type T
. The cast may be allowed erroneously, which may trigger problems later.
It is not a huge problem; usually when the programmer does (T)o
, he has already reasoned that the cast is safe, and won't cause any problem at runtime. The cast is checked by app logic.
Suppose a Class<T> clazz
is available at the point of cast, then we do know what T
is at runtime; we can add extra runtime check to make sure o
is indeed a T
.
check clazz.isInstance(o);
(T)o;
And this is essentially what Class.cast()
does.
We would never expect the cast to fail in any case, therefore in a correctly implemented app, check clazz.isInstance(o)
must always succeed anway, therefore clazz.cast(o)
is equivalent to (T)o
- once again, under the assumption that the code is correct.
If one can prove that the code is correct and the cast is safe, one could prefer (T)o
to clazz.cast(o)
for performance reason. In the example of MutableClassToInstanceMap
raised in another answer, we can see obviously that the cast is safe, therefore simple (T)o
would have sufficed.
(Number) o
since a cast has no influence over the actual type of an object. – Orator