1

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?

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 1
    You can dissamble a .class using `javap -c ...` – Joop Eggen May 13 '15 at 11:47
  • Roughly the same effect, different instructions. The second is less efficient and is only really of use when you're using generics. – Hot Licks May 13 '15 at 11:52
  • 1
    The answer that this one is supposedly a duplicate of, doesn't answer the question whether the two approaches result in the same bytecode (which they do not, as I've demonstrated). – Anders R. Bystrup May 13 '15 at 12:02

2 Answers2

4

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,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1

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);
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74