What is the difference between these two ways of casting in Java?
(CastingClass) objectToCast;
CastingClass.class.cast(objectToCast);
The source of Class#cast(Object)
is as follows:
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException();
return (T) obj;
}
So, cast
is basically a generic wrapper of the cast operation, but I still don't understand why you would need a method for it.
You can only use the first form for statically linked classes.
In many cases that's not enough - for example, you may have obtained class instance using reflection or it was passed to your method as parameter; hence the second form.
Because you cannot just write (T)objectToCast
, when T
is a generic type parameter (due to type erasure). Java compiler will let you do that, but T
will be treated as Object
there, so the cast will always succeed, even if the object you're casting isn't really an instance of T
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With