![](/img/trans.png)
[英]How do I avoid “potential null pointer access” when using Preconditions.checkNotNull()?
[英]Preconditions checknotnull annotations produce null warnings
以下行
final ProgramObject data =
Preconditions.checkNotNull(datas.get(name), TEMPLATE, name);
在 android 工作室發出警告
警告:(291, 44) 參數 'data.get(name)' 可能是 null
在查看 Preconditions 的源代碼時:
@CanIgnoreReturnValue
@NonNullDecl
public static <T extends Object> T checkNotNull(
@NonNullDecl T obj, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1) {
if (obj == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return obj;
}
看起來第一個參數不允許獲取 null。
這是與其相關的 PR: https://github.com/google/guava/commit/a890c444e55973384d1370b56afe1a02e7db9c3c
所以我想知道:
顯然,如果我進行 null 檢查,我懷疑參數可能是 null
Preconditions.checkNotNull
的意圖是它應該只用於您認為永遠不可能是 null 的變量——並且您想確保您的信念是正確的,並且如果您錯了則拋出異常。
Guava 的設置按預期工作。 您可能適合取消警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.