在Java中,判断一个字符串是否为空或者为 null
是一个常见的操作。以下是几种常见的方法来实现这个判断:
1. 使用 ==
和 isEmpty()
这是最基础的方式,用来判断字符串是否为 null
或者为空字符串。
String str = ...;
if (str == null || str.isEmpty()) {
// 字符串为 null 或空字符串
}
2. 使用 ==
和 length()
另一种方式是检查字符串的长度是否为0。
String str = ...;
if (str == null || str.length() == 0) {
// 字符串为 null 或空字符串
}
3. 使用 Apache Commons Lang
如果你使用了Apache Commons Lang库,可以使用 StringUtils
类,它提供了更加简洁的方法。
首先,需要在你的项目中添加依赖(如果使用Maven):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- 请根据需要选择版本 -->
</dependency>
然后,可以使用如下方法:
import org.apache.commons.lang3.StringUtils;
String str = ...;
if (StringUtils.isEmpty(str)) {
// 字符串为 null 或空字符串
}
4. 使用 Java 11 的 isBlank()
Java 11 引入了 String
类的新方法 isBlank()
,它不仅检查字符串是否为空,还会检查字符串是否只包含空白字符(如空格、制表符等)。
String str = ...;
if (str == null || str.isBlank()) {
// 字符串为 null、空字符串或仅包含空白字符
}
5. 使用 Objects
类的 requireNonNullElse
方法
在需要提供默认值的情况下,可以使用 Objects
类的 requireNonNullElse
方法,它可以在字符串为 null
时提供一个默认值。
import java.util.Objects;
String str = ...;
str = Objects.requireNonNullElse(str, "");
if (str.isEmpty()) {
// 字符串为 null 或空字符串
}
示例
import org.apache.commons.lang3.StringUtils;
public class StringTest {
public static void main(String[] args) {
String str1 = null;
String str2 = "";
String str3 = " ";
// 方法1: 使用 == 和 isEmpty()
if (str1 == null || str1.isEmpty()) {
System.out.println("str1 is null or empty");
}
if (str2 == null || str2.isEmpty()) {
System.out.println("str2 is null or empty");
}
// 方法2: 使用 == 和 length()
if (str2 == null || str2.length() == 0) {
System.out.println("str2 is null or empty");
}
// 方法3: 使用 Apache Commons Lang
if (StringUtils.isEmpty(str2)) {
System.out.println("str2 is null or empty (using StringUtils)");
}
// 方法4: 使用 Java 11 的 isBlank()
if (str3 == null || str3.isBlank()) {
System.out.println("str3 is null, empty or blank");
}
// 方法5: 使用 Objects 的 requireNonNullElse
str1 = Objects.requireNonNullElse(str1, "");
if (str1.isEmpty()) {
System.out.println("str1 is null or empty (using Objects.requireNonNullElse)");
}
}
}