三元运算符 报错 java.lang.NullPointerException

版权声明:转载请注明出处,谢谢。 https://blog.csdn.net/weixin_40413816/article/details/82839409
@Setter
@Getter
@ToString
public class Student {
	
	private Integer age;
	private Integer year;	
}
public static void main(String[] args) {
		Student stu = new Student();
		stu.setAge(1);
		stu.setYear(null);
		System.out.println(stu == null ? 0 : stu.getYear());
	}

这样会报空指针

原因是: JDK在做自动拆装箱的时候调用了Integer.intValue()方法, 导致空指针

解决方法:
1、 避免值为null的情况.
2、 写成包装类:

public static void main(String[] args) {
		Student stu = new Student();
		stu.setAge(1);
		stu.setYear(null);
		System.out.println(stu == null ? new Integer(0) : stu.getYear());
	}

猜你喜欢

转载自blog.csdn.net/weixin_40413816/article/details/82839409