3

Let's say that I have the following:

int a = 2;
Number b = (Number) a;

System.out.println(b); // Prints 2

http://java.sun.com/docs/books/jls/first_edition/html/15.doc.html#238146 says that a primitive value may not be cast to a reference type. Does Java know to create an Integer from the primitive int and then cast to the superclass? How exactly does Java handle this behind the scenes? Thanks!

4

1 回答 1

3

The process is called autoboxing. In short, the compiler sees that a wrapper (Integer) rather than a primitive (int) is needed and automatically adds the conversion. And actually your cast to Number is not necessary.

于 2010-03-17T19:08:18.617 回答