欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA - 【Optional】辅助防止空指针异常

程序员文章站 2022-03-04 11:28:38
...

Optional是JDK1.8新增的类,在JDK1.8之前一般某个函数应该返回非空对象,但是偶尔会返回null,在JDK1.8中,不推荐直接返回该对象,返回之前需要进行处理;

☞ 关键:Optional.ofNullable(s).get()



  • 一般情况

由于对象元素没有初始化,运行会直接在s.getName处报空指针异常,但是究竟是哪一个deal造成的空指针异常?

 JAVA - 【Optional】辅助防止空指针异常

public class Main{
	public static void main(String[] args) {
		
		Student s = new Student();
		s = deal1(s);
		s = deal2(s);
		s = deal2(s);
		String name = s.getName();
		System.out.println(name);
	}
	
	public static Student deal1(Student s){
		s = null;
		return s;
	}
	public static Student deal2(Student s){
		s = null;
		return s;
	}
	public static Student deal3(Student s){
		s = null;
		return s;
	}
}
  • Optional优化

      JAVA - 【Optional】辅助防止空指针异常

import java.util.Optional;

public class Main{
	public static void main(String[] args) {
		
		Student s = new Student();
		s = deal1(s);
		s = deal2(s);
		s = deal2(s);
		String name = s.getName();
		System.out.println(name);
	}
	public static Student deal1(Student s){
		s = null;
		return Optional.ofNullable(s).get();
	}
	public static Student deal2(Student s){
		s = null;
		return Optional.ofNullable(s).get();
	}
	public static Student deal3(Student s){
		s = null;
		return Optional.ofNullable(s).get();
	}
}

 

 

JAVA - 【Optional】辅助防止空指针异常