包装类 - 拆装箱
包装类的
引用类型
和基本数据类型
之间的转换 - 关于自动装箱和自动拆箱。
复制代码
1
2
3Integer n = 100; int x = n;
自动装箱
-
对
Integer n = 100;
反汇编可以得到下面指令:复制代码1
2
3
4
52: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
即:调用类的静态方法。
-
然后看
Integer
的源码可以发现,valueOf
的所有声明:复制代码1
2
3
4public static Integer valueOf(int i) {...} public static Integer valueOf(String s) throws NumberFormatException {...} public static Integer valueOf(String s, int radix) throws NumberFormatException {...}
即:全部被声明为了静态方法。
-
编译器自动调用了
Integer
类的valueOf
方法。
自动拆箱
-
对
int x = n;
反汇编可得:复制代码1
2
37: invokevirtual #3 // Method java/lang/Integer.intValue:()I
即:调用对象的实例方法。
-
Integer
源码中intValue()
的声明:复制代码1
2public int intValue() {...}
-
编译器自动调用了
Integer
类的intValue()
方法。
小结
- 编译器在编译的时候会自动调用
Integer.intValue()
和Integer.valueOf(...)
完成int
和Integer
之间的转换。
最后
以上就是柔弱店员最近收集整理的关于包装类 - 拆装箱包装类 - 拆装箱的全部内容,更多相关包装类内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复