Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two ways of casting in Java?

Tags:

java

casting

What is the difference between these two ways of casting in Java?

  1. (CastingClass) objectToCast;

  2. 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.

like image 645
Ben Simmons Avatar asked Nov 12 '09 20:11

Ben Simmons


2 Answers

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.

like image 190
ChssPly76 Avatar answered Oct 09 '22 04:10

ChssPly76


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.

like image 25
Pavel Minaev Avatar answered Oct 09 '22 06:10

Pavel Minaev