It's does the same. But if you look at the implementation:
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
it becomes obvious that there's some extra checking done by the method. What that translates to in bytecode can be seen using javap -c
on a class resembling your example:
This is the simple direct cast:
0: aload_0
1: getfield #2; //Field o:Ljava/lang/Object;
4: checkcast #3; //class java/lang/Integer
7: astore_1
This is using the Class.cast()
method:
11: aload_0
12: getfield #2; //Field o:Ljava/lang/Object;
15: invokevirtual #4; //Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
18: checkcast #3; //class java/lang/Integer
21: astore_2
As can be seen, there is the overhead of the invokevirtual
operation, congruent with the fact that the end class might not be known with this approach (as @screenmutt writes in his answer).
Cheers,