![](/img/trans.png)
[英]What is the best way to check string not null and not empty in Java?
[英]Best method to check if a value of a String is null in Java
關於如何檢查 String 值是否為 null 的實現有很多,我真的很困惑該用什么!
到目前為止,這些是我的搜索:
if(myString == null){}
Objects.equals(null, myString);
ObjectUtils.isEmpty(myString)
myString.equals(null)
myString.compareTo(null);
注意:這都是關於性能、可靠編碼、故障安全和其他安全目的!
更新: myString 是動態的,如果它是 null 怎么辦,上面的一些實現會拋出 NullPointerException!
只需使用一個簡單的==
。 沒有必要將其復雜化。
另一種選擇,如果您使用的是 Java 8,則可以使用Optional::ofNullable
Optional.ofNullable(myString).isPresent()// true if not null, false if null
你甚至可以使用:
Optional.ofNullable(myString)
.orElseThrow(() -> new Exception("If null throw an exception"));
有很多選項,只需閱讀文檔
但正如Mureinik在他的回答中提到的那樣==
對你來說就足夠了。
if(myString == null)
最簡單正確的方法。
Objects.equals(null, myString)
一個正確的方法,它的實現基於1。
ObjectUtils.isEmpty(myString)
不確定您正在使用哪個ObjectUtils
,但它似乎檢查myString
是否為空,而不是 null。
myString.equals(null)
當myString
為 null 時,這不起作用,將拋出 NPE。
myString.compareTo(null)
當myString
為 null 時,這不起作用,將拋出 NPE。
`
String results;
if(results==null ||results.length()==0) {
}
`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.