What about isEmpty() ?
(那isEmpty()呢?)
if(str != null && !str.isEmpty())
Be sure to use the parts of &&
in this order, because java will not proceed to evaluate the second part if the first part of &&
fails, thus ensuring you will not get a null pointer exception from str.isEmpty()
if str
is null.
(确保按此顺序使用&&
的部分,因为如果&&
的第一部分失败,java将不会继续评估第二部分,因此,如果str
为null,则确保不会从str.isEmpty()
获得null指针异常。 。)
Beware, it's only available since Java SE 1.6.
(请注意,仅从Java SE 1.6起可用。)
You have to check str.length() == 0
on previous versions. (您必须在以前的版本中检查str.length() == 0
。)
To ignore whitespace as well:
(也要忽略空格:)
if(str != null && !str.trim().isEmpty())
(since Java 11 str.trim().isEmpty()
can be reduced to str.isBlank()
which will also test for other Unicode white spaces)
((因为Java 11 str.trim().isEmpty()
可以简化为str.isBlank()
,这也将测试其他Unicode空格))
Wrapped in a handy function:
(包裹在一个方便的功能中:)
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
Becomes:
(成为:)
if( !empty( str ) )
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…