簡體   English   中英

使用Preconditions.checkNotNull()時,如何避免“潛在的空指針訪問”?

[英]How do I avoid “potential null pointer access” when using Preconditions.checkNotNull()?

Eclipse給我警告“潛在空指針訪問:變量ann在此位置可能為null”:

SomeAnnotation ann = type.getAnnotation( SomeAnnotation.class );
Preconditions.checkNotNull( ann, "Missing annotation on %s", type );

for( String value : ann.value() ) { // <-- warning happens here
}

我正在使用Eclipse 3.7和Guava 有沒有辦法擺脫這個警告?

我可以使用SuppressWarnings("null")但我必須將它附加到我認為不太好的方法。

Eclipse e4對編譯器中的空檢查和資源跟蹤有更好的支持。

另一種解決方案是編寫自己的checkNotNull版本,如下所示:

@Nonnull
public static <T> T checkNotNull(@Nullable T reference) {
  if (reference == null) {
    throw new NullPointerException();
  }
  return reference;   
}

現在你可以使用這種方法:

SomeAnnotation ann = Preconditions.checkNotNull( type.getAnnotation( SomeAnnotation.class ) );

(我省略了checkNotNull()錯誤消息的checkNotNull()版本;它們以相同的方式工作)。

我想知道為什么Guava沒有這樣做,因為他們已經在其他地方使用了這些注釋。

你可以停止使用Eclipse。

嘿,這是一個解決方案。 它可能不是你想要的那個,但它解決了問題,並不是一個真正糟糕的解決方案。

更嚴重的是,您可以:

  • 調整編譯器警告設置,
  • 在方法或類級別使用SuppressWarnings
  • 使用更現代的編譯器(顯然更新的版本不會為簡單的情況觸發),
  • 重寫您的代碼,並將checkNotNull的返回值賦給ann

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM