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

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)方法;

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

猜你喜欢

转载自blog.csdn.net/weixin_43041241/article/details/88680431