简体   繁体   中英

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

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.

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 .

This first is an ordinary cast. It requires that the type to cast to is known at compile time. It verifies at compile time that the cast can be correct, and checks (if the type to cast to is not generic) that the cast is correct at runtime.

The second uses the reflection api. It requires that the class to cast to is known at runtime. It doesn't verify anything at compile time, but always checks that the cast is correct at runtime.

Type parameters are only known at compile type, hence you can not use the second approach for a type parameter (the expression T.class does not compile).

Dynamically loaded classes (for instance with Class.forName(String)) are only known at runtime, hence the first approach can not be used.

Edit: However, as Pavel points out, it makes no sense to cast to a dynamically loaded class. I agree that the only real usefulness of Class.cast(Object) is to cast to a type parameter for which you happen to have a class object available.

If the type to cast to does not contain a type parameter, the first approach is better, as the additional compile time checking can catch bugs, you lose no type safety at runtime, and get a shorter syntax to boot.

In the first one you have to hardcode the casting class.

( ClassToCast ) objectToCast;

In the second one the casting class maybe a parameter:

Class toCast = getClassToCast();

toCast.cast( objectToCast );

Here you can find an use example wherein Class#cast() is used. It may give new insights.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM