JAVA - 【Optional】輔助防止空指針異常

Optional是JDK1.8新增的類,在JDK1.8之前一般某個函數應該返回非空對象,但是偶爾會返回null,在JDK1.8中,不推薦直接返回該對象,返回之前需要進行處理;

☞ 關鍵:Optional.ofNullable(s).get()



  • 一般情況

由於對象元素沒有初始化,運行會直接在s.getName處報空指針異常,但是究竟是哪一個deal造成的空指針異常?

 

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優化

     

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();
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章