将原始 int 转换为 Number
假设我有以下内容:
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 表示原始值不能转换为引用类型。 Java 是否知道从原始 int 创建一个 Integer 然后转换为超类? Java 在幕后到底是如何处理这个问题的?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该过程称为“自动装箱”。简而言之,编译器发现需要包装器 (
Integer
) 而不是基元 (int
),并自动添加转换。实际上,您没有必要将其转换为Number
。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 toNumber
is not necessary.