這個問題在這里已經有了答案: Java:字串到布林值 1 個答案 8 天前關閉。
當使用 Boolean.valueOf(String) 方法時,如果給定除“true”之外的任何字串,則回傳值為 false。這個 try 塊似乎永遠不會失敗,即使它應該失敗?
boolean a;
String b = "randomTextThatsNotTrueOrFalse";
try{
a= Boolean.valueOf(b);
}
catch(IllegalArgumentException e) {
LOG.error(b "is invalid. Only true or false are possible Options.");
}
uj5u.com熱心網友回復:
根據規范(并且,正如預期的那樣,OpenJDK 實作的源代碼遵循此規范),"true"
(使用任何大小寫)被決議為true
,所有其他字串被決議為false
:
* Returns a {@code Boolean} with a value represented by the * specified string. The {@code Boolean} returned represents a * true value if the string argument is not {@code null} * and is equal, ignoring case, to the string {@code "true"}. * Otherwise, a false value is returned, including for a null * argument.
閱讀 javadoc 很重要;你應該養成它的習慣。
如果您想要一個方法,true
如果通過"true"
,false
如果通過,則回傳,"false"
否則拋出 IAEx,您必須自己撰寫。這是大約 80 個字符的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494841.html