IDEA中習慣跟蹤源碼實現邏輯,多次碰到Objects.requireNonNull(T obj)這個方法,改方法主要用於提早判斷對象是否為空,以便更早的拋出NPE
平時小組開發中強調程序健壯性,不允許組員的代碼中出現明顯的NPE,這樣多數時候都要寫判空邏輯,拋出自定義的異常
我們看下具體的源碼:
/**
* Checks that the specified object reference is not {@code null}.
* This method is designed primarily for doing parameter validation in methods
* and constructors, as demonstrated below:
* <blockquote><pre>
* public Foo(Bar bar) {
* this.bar = Objects.requireNonNull(bar);
* }
* </pre></blockquote>
*
* @param obj the object reference to check for nullity
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
*/
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
解釋:檢查定義的對象引用不為空。設計該方法主要用來做方法和構造函數中的參數校驗
如上,如果直接使用仍然是拋出一個NPE,除了能提早檢測和拋出異常,無法直接在業務中使用
繼續往下滾動,發現還有這個方法
/**
* Checks that the specified object reference is not {@code null} and
* throws a customized {@link NullPointerException} if it is. This method
* is designed primarily for doing parameter validation in methods and
* constructors with multiple parameters, as demonstrated below:
* <blockquote><pre>
* public Foo(Bar bar, Baz baz) {
* this.bar = Objects.requireNonNull(bar, "bar must not be null");
* this.baz = Objects.requireNonNull(baz, "baz must not be null");
* }
* </pre></blockquote>
*
* @param obj the object reference to check for nullity
* @param message detail message to be used in the event that a {@code
* NullPointerException} is thrown
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
*/
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}
and throws a customized {@link NullPointerException} if it is:定制的空指針異常
and constructors with multiple parameters :多參數的構造函數
這樣,下次我們想拋出一個自定義的空指針異常的時候,以前是:
if(obj==null){
throw new xxxException("該記錄不存在xxxx");
}
現在可以更優雅的寫Objects.requireNonNull(T obj,"該記錄不存在xxxx")
代碼實現區別不大,那么為啥不選擇優雅^_^
