St.Antario
St.Antario

Reputation: 27375

Is there any difference in those two way of casting?

In the following code

Object o;

//getting o

Integer i = (Integer) o; //1
Integer j = Integer.class.cast(mapValue);  //2

is there any difference between //1 and //2?

I mean, in JVM all those cases are going to be carried out with the same bytecode instructions, is that right?

Upvotes: 1

Views: 88

Answers (2)

Dan Grahn
Dan Grahn

Reputation: 9404

As Anders points out, the effect is the same.

However, you can only use the first if you know the end class. In this example, you can cast without knowing the end class.

Class toCast = getClassToCast();
toCast.cast(objectToCast);

Upvotes: 1

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16050

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,

Upvotes: 4

Related Questions