[英]How can i fix this method so it returns null if the car type is not found
[英]How can I annotate my helper method so Eclipse knows its argument is non null if it returns true?
我有一個輔助方法hasContent(String)
,如果其參數非空且至少包含一個非空白字符,則返回true。 我剛剛在Eclipse中啟用了null分析,我發現當我使用這個方法來執行一個代碼塊時,這個代碼塊是以我的helper函數的結果為條件的,表明字符串有內容(因此不能為null),盡管如此Eclipse抱怨我的String可能仍為null。
輔助功能
public static boolean hasContent(String text) {
if (text == null)
return false;
if (text.trim().length() == 0)
return false;
return true;
}
使用示例
...
String dataString;
try {
dataString = readStringFromFile("somefile.txt");
} catch (IOException e) {
System.err.println("Failed to read file due to error: " + e);
dataString = null;
}
// At this point dataString may be null
if (hasContent(dataString)) {
// At this point dataString must be non-null, but Eclipse warns:
// "Potential null pointer access: The variable dataString may be null at this location"
// at the following reference to dataString
System.out.println("Read string length " + dataString.length());
}
...
這種情況的最佳做法是什么? 如果可以避免,我不想壓制警告。 我更願意告訴Eclipse,如果hasContent()
返回true
那么它的參數肯定是非null。 這可能嗎? 如果是這樣,怎么樣?
你的方法的契約是如果hasContent
返回true,那么它的參數保證是非null的。
Eclipse無法在編譯時表達或檢查此合同,至少在不更改代碼和降低其樣式的情況下。
Nullness Checker是一個不同的工具,可以在編譯時表達和檢查此合同。 它不需要您更改代碼就可以。 您只需添加@EnsuresNonNullIf
注釋您的代碼:
@EnsuresNonNullIf(expression="#1", result=true)
public static boolean hasContent(String text) { ...
Nullness Checker隨Checker Framework一起分發。 有一個Eclipse插件 ,可以讓你在Eclipse中運行Nullness Checker。
它可能不是最佳實踐,但是:如果拋出IOException,則可以返回false,或者只是將變量設置為false。 如果沒有,您可以將變量設置為true(在try-block中)。
try {
dataString = readStringFromFile("somefile.txt");
hasContent = true;
} catch (IOException e) {
System.err.println("Failed to read file due to error: " + e);
hasContent = false;
}
我無法看到你正在嘗試的方法。
您可以修改hasContent
以返回它傳遞的字符串,而不是boolean
,如果參數為null或為空,則拋出Exception
。 然后,您將使用@NonNull
注釋該函數。 然而,這會以我懷疑你不喜歡的方式破壞你的調用代碼,因為它必須使用try
/ catch
邏輯而不是if
。
這將使hasContent
函數:
@NonNull
public static String hasContent(String text) throws Exception {
if (text == null)
throw new Exception( "Null string" );
if (text.trim().length() == 0)
throw new Exception( "Empty string" );
return text;
}
和調用代碼:
...
try {
dataString = readStringFromFile("somefile.txt");
} catch (IOException e) {
System.err.println("Failed to read file due to error: " + e);
dataString = null;
}
// At this point dataString may be null
try {
dataString = validateHasContent( dataString );
// At this point dataString must be non-null
System.out.println("Read string length " + dataString.length());
} catch( Exception e ) {
}
...
如果您准備做出這種妥協,那么專門的例外顯然會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.