What is the difference between these two casting methods in Java?

What is the difference between these two casting methods in Java?

  • (CastingClass) objectToCast;

  • CastingClass.class.cast(objectToCast);

The source is Class#cast(Object)as follows:

public T cast(Object obj) {
if (obj != null && !isInstance(obj))
    throw new ClassCastException();
return (T) obj;
}

So, castbasically it is the general wrapper of a translation operation, but I still don't understand why you need a method for it.

+5
source share
5 answers

You can use only the first form for statically related classes.

In many cases, this is not enough - for example, you can get an instance of a class using reflection or it was passed to your method as a parameter; hence the second form.

+7
source

(T)objectToCast, T (- ). Java , T Object, , , , T.

+4

. , , , . , , ( , , ), .

api. , , , . , .

, ( T.class ).

(, Class.forName(String)) , .

: , , . , Class.cast(Object) , .

cast to , , , .

+2
source

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

( ClassToCast ) objectToCast;

In the second class, the cast can have a parameter:

Class toCast = getClassToCast();

toCast.cast( objectToCast );
+1
source

Here you can find an example of use in which it is used Class#cast(). This may give new ideas.

0
source

All Articles