[英]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.