java 编译器优化+自动装箱

一、编译器优化+自动装箱

 

1. Dog验证类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Dog {

    private String name;
    List<String> strings;
    private Long thresholdTime;
}

2. Test测试类

public class TestMain1 {
    public static void main(String[] args) {
        System.out.println(getThresoldTimes());
    }

    public static Long getThresoldTimes(){
        Dog dog = new Dog();
        dog.setName("111");

        return dog == null?-1:dog.getThresholdTime();
    }
}

3. 允许结果【出现空指针异常】

Exception in thread "main" java.lang.NullPointerException
	at com.luoyu.aiyu.luo1.TestMain1.getThresoldTimes(TestMain1.java:25)
	at com.luoyu.aiyu.luo1.TestMain1.main(TestMain1.java:18)

分析——编译后的class文件:

public class TestMain1
{
    public static void main(String[] args) {
        System.out.println(getThresoldTimes());
    }
    
    public static Long getThresoldTimes() {
        Dog dog = new Dog();
        dog.setName("111");
        
        return Long.valueOf((dog == null) ? -1L : dog.getThresholdTime().longValue());
    }
}

再次分析:

注:重新验证Test

public class TestMain1 {
    public static void main(String[] args) {
        System.out.println(getThresoldTimes());
    }

    public static Long getThresoldTimes(){
        Long a = -1L;

        return a;
    }
}

注:重新验证Test.class 

public class TestMain1
{
    public static void main(String[] args) {
        System.out.println(getThresoldTimes());
    }
    
    public static Long getThresoldTimes() {
        Long a = Long.valueOf(-1L);
        
        return a;
    }
}

这里说明:执行的Long.valueOf代表的是自动装箱。。。因为Long本身就是对象

同时:如下代码,1L表示long 1。根据编译器自动装箱,需要将这里的表达式转换为:Long a = Long.valueOf(1L);

Long a = 1L;

 这里为什么需要Long.valueOf呢?因为-1L代表的是long 而 testLong()代表的是Long

最后统一需要转换成Long。

本质上:用的是这个方法:所以testLong()需要先将Long转换成long,故使用了longValue()方法 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值