包装类和基本数据类型自动拆装包的实现原理

通过反编译Java的class文件,分析包装类自动拆箱和装箱原理。自动拆箱是包装类调用typeValue()方法,若包装类为NULL会报空指针异常;自动装箱调用Integer.valueOf(int)方法;两个类型用==比较时,包装类会先拆箱再比较。

java源码

	public static void main(String[] arg0) {
        Integer i = null;
        int y = i;
        System.out.println(y);
	
		Integer z = 2;
		int a = 3;
		int aaa = 155;
		int aaaa = 255555;
		System.out.println(z==a);
		Integer zb = new Integer("3");
		int za = z;
	}

反编译class文件

    public static void main(String args[])
    {
        Integer integer = null;
        int i = integer.intValue();
        System.out.println(i);
        Integer integer1 = Integer.valueOf(2);
        byte byte0 = 3;
        char c = '\233';
        int j = 0x3e643;
        System.out.println(integer1.intValue() == byte0);
        Integer integer2 = new Integer("3");
        int k = integer1.intValue();
    }

可以看到,包装类自动拆包原理:是通过包装类调用typeValue()方法,因此如果包装类为NULL,会报空指针异常。

自动装箱:调用的是Integer.valueOf(int)方法;

两个类型做==比较,包装类会下拆箱再比较。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值