杰瑞科技汇

Java对象为空如何高效判断?

判断对象是否为 null

这是最基本、最直接的判断,如果一个变量没有被初始化,或者被显式地赋值为 null,那么它就是一个空对象。

Java对象为空如何高效判断?-图1
(图片来源网络,侵删)

方法: 使用 操作符。

public class MyClass {
    private String name;
    public MyClass(String name) {
        this.name = name;
    }
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "Hello";
        MyClass obj1 = null;
        MyClass obj2 = new MyClass("Java");
        // 判断基本类型引用
        if (str1 == null) {
            System.out.println("str1 是 null"); // 会执行
        }
        if (str2 != null) {
            System.out.println("str2 不是 null"); // 会执行
        }
        // 判断自定义对象
        if (obj1 == null) {
            System.out.println("obj1 是 null"); // 会执行
        }
        if (obj2 != null) {
            System.out.println("obj2 不是 null"); // 会执行
        }
    }
}

⚠️ 重要注意事项:

  • 永远不要对一个 null 对象调用方法或访问属性,否则会抛出 NullPointerException
  • 比较的是对象的内存地址(引用),对于基本类型(如 int, double), 比较的是值;但对于所有对象类型(包括包装类如 Integer, String), 比较的是它们是否指向同一个内存地址。

判断字符串是否为空

字符串是“空”概念最复杂的场景之一,因为它可能包含以下几种情况:

  • null:未初始化。
  • 一个空字符串,长度为 0。
  • 一个只包含空格的字符串,通常也被认为是“空”的。

1 判断 null 或 (空字符串)

这是最常见的字符串空值判断。

Java对象为空如何高效判断?-图2
(图片来源网络,侵删)

方法:

  • Java 8+: 使用 String 类自带的 isEmpty() 方法。
  • 传统方法: 先判断 != null,再判断 length() == 0
String str1 = null;
String str2 = "";
String str3 = "Hello";
// Java 8+ 推荐
if (str1 == null || str1.isEmpty()) {
    System.out.println("str1 是 null 或空字符串"); // 会执行
}
// 传统方法 (同样有效)
if (str2 != null && str2.length() == 0) {
    System.out.println("str2 是 null 或空字符串"); // 会执行
}
if (str3 != null && !str3.isEmpty()) {
    System.out.println("str3 不是空字符串"); // 会执行
}

2 判断 null、 或纯空格字符串

方法:

  • Java 11+: 使用 String.isBlank() 方法,这是最简单、最推荐的方式。
  • 传统方法:isEmpty() 基础上,用 trim() 去除首尾空格后再判断。
String str1 = null;
String str2 = "";
String str3 = "   ";
String str4 = "  Java  ";
// Java 11+ 推荐
if (str1 == null || str1.isBlank()) {
    System.out.println("str1 是 null、空或纯空格"); // 会执行
}
if (str3.isBlank()) {
    System.out.println("str3 是 null、空或纯空格"); // 会执行
}
// 传统方法
if (str2 != null && str2.trim().isEmpty()) {
    System.out.println("str2 是 null、空或纯空格"); // 会执行
}
if (!str4.isBlank()) {
    System.out.println("str4 不是 null、空或纯空格"); // 会执行
}

判断集合、数组是否为空

集合(如 List, Set, Map)和数组也有“空”的概念。

1 集合 (List, Set, Map)

“空”通常指:

  • null:集合对象本身是 null
  • size() == 0:集合被初始化了,但没有元素。

方法:

  • Guava (Google Core Libraries): com.google.common.base.Strings.isNullOrEmpty() 适用于 CharSequence,但不直接适用于 Collection,更常用的是 com.google.common.collect.Iterables.isEmpty()Collections.isEmpty()
  • Apache Commons Lang: CollectionUtils.isEmpty() 是一个非常流行且方便的工具。
  • Java 标准库: 推荐 Objects.requireNonNullElseOptional,或者手动判断。
import java.util.*;
import java.util.stream.Collectors;
public class CollectionEmptyCheck {
    public static void main(String[] args) {
        List<String> list1 = null;
        List<String> list2 = new ArrayList<>();
        List<String> list3 = Arrays.asList("A", "B");
        // 1. 手动判断 (最通用)
        if (list1 == null || list1.isEmpty()) {
            System.out.println("list1 是 null 或空列表"); // 会执行
        }
        if (list2.isEmpty()) {
            System.out.println("list2 是空列表"); // 会执行
        }
        // 2. Java 8+ Optional (推荐,更优雅)
        Optional.ofNullable(list3).ifPresent(l -> System.out.println("list3 不为空,大小: " + l.size())); // 会执行
        // 3. Apache Commons Lang (非常流行)
        // 需要依赖: org.apache.commons:commons-lang3
        // System.out.println(CollectionUtils.isEmpty(list1)); // true
        // System.out.println(CollectionUtils.isEmpty(list2)); // true
        // System.out.println(CollectionUtils.isEmpty(list3)); // false
        // 4. Java 9+ Objects.requireNonNullElse
        // List<String> safeList = Objects.requireNonNullElse(list1, Collections.emptyList());
        // System.out.println(safeList.isEmpty()); // true
    }
}

2 数组 (Array)

“空”指:

  • null:数组对象本身是 null
  • length == 0:数组被初始化了,但没有元素。

方法:

String[] arr1 = null;
String[] arr2 = new String[0]; // 空数组
String[] arr3 = new String[]{"A", "B"};
// 手动判断
if (arr1 == null || arr1.length == 0) {
    System.out.println("arr1 是 null 或空数组"); // 会执行
}
if (arr2.length == 0) {
    System.out.println("arr2 是空数组"); // 会执行
}

使用工具类进行统一判断

为了避免在每个地方都写 == null.isEmpty() 这样的样板代码,强烈推荐使用工具类。

1 Apache Commons Lang3

这是最广泛使用的工具库之一。

Maven 依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version> <!-- 使用最新版本 -->
</dependency>

核心方法:

  • ObjectUtils.isEmpty(Object obj): 通用方法,可以判断 null、空字符串、空集合、空数组。
  • StringUtils.isBlank(CharSequence cs): 判断 null、空字符串、纯空格字符串。
  • StringUtils.isEmpty(CharSequence cs): 判断 null、空字符串。
  • CollectionUtils.isEmpty(Collection coll): 判断 null 或空集合。
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
public class CommonsLangExample {
    public static void main(String[] args) {
        String str = null;
        List<String> list = null;
        int[] arr = null;
        // 通用对象判断
        System.out.println(ObjectUtils.isEmpty(str));   // true
        System.out.println(ObjectUtils.isEmpty(list));  // true
        System.out.println(ObjectUtils.isEmpty(arr));   // true
        System.out.println(ObjectUtils.isEmpty(""));   // true
        System.out.println(ObjectUtils.isEmpty(" "));  // false (注意)
        System.out.println(ObjectUtils.isEmpty("abc")); // false
        // 字符串专用判断
        System.out.println(StringUtils.isBlank(str));   // true
        System.out.println(StringUtils.isBlank(""));    // true
        System.out.println(StringUtils.isBlank(" "));   // true
        System.out.println(StringUtils.isBlank("abc")); // false
    }
}

2 Java 8+ java.util.Objects

Java 8 自带的 Objects 类也提供了一些有用的静态方法。

  • Objects.requireNonNull(T obj): 如果对象为 null,抛出 NullPointerException
  • Objects.requireNonNullElse(T obj, T defaultObj): 如果对象为 null,返回 defaultObj,否则返回原对象,非常适合提供默认值。
import java.util.Objects;
public class JavaObjectsExample {
    public static void main(String[] args) {
        String name = null;
        String defaultName = "Guest";
        // 提供默认值,避免返回 null
        String finalName = Objects.requireNonNullElse(name, defaultName);
        System.out.println(finalName); // 输出: Guest
        name = "Alice";
        finalName = Objects.requireNonNullElse(name, defaultName);
        System.out.println(finalName); // 输出: Alice
    }
}

总结与最佳实践

场景 推荐方法 备注
通用对象是否为 null if (obj == null) 最基础,必须掌握。
字符串是否为 null if (str == null || str.isEmpty()) Java 8+ 标准做法。
字符串是否为 null、 或纯空格 if (str == null || str.isBlank()) 强烈推荐,Java 11+,如果用旧版本,用 str.trim().isEmpty()
集合是否为 nullsize()==0 if (coll == null || coll.isEmpty()) 或使用 Optional.ofNullable(coll).ifPresent(...)
数组是否为 nulllength==0 if (arr == null || arr.length == 0) 标准做法。
统一、简洁的判断 (推荐) 使用 Apache Commons Lang3 ObjectUtils.isEmpty(), StringUtils.isBlank() 等,能极大简化代码,提高可读性。
避免 NullPointerException 使用 OptionalObjects.requireNonNullElse 提供默认值或优雅地为空值提供处理逻辑,是现代 Java 编程的推荐实践。

核心思想:

  1. 明确“空”的定义:你的业务逻辑中,“空”到底指什么?是 null?还是长度为 0?还是包含无效内容(如空格)?
  2. 防御性编程:始终考虑传入的对象可能为 null 的情况,提前进行判断,避免程序崩溃。
  3. 拥抱工具库:不要重复造轮子,像 Apache Commons Lang3 这样的成熟库已经为我们处理了各种边界情况,使用它们能让代码更健壮、更简洁。
分享:
扫描分享到社交APP
上一篇
下一篇