Apache Commons 完全指南:ObjectUtils、ArrayUtils、BooleanUtils 的用法

ObjectUtils、ArrayUtils、BooleanUtils

java 复制代码
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;

// ===== ObjectUtils =====
ObjectUtils.defaultIfNull(value, "默认值");
ObjectUtils.firstNonNull(a, b, c, "兜底");      // 返回第一个非 null
ObjectUtils.isEmpty(collection);                // 支持 String/Collection/Map/数组/Optional
ObjectUtils.isNotEmpty(array);
ObjectUtils.max(1, 5, 3);                       // 可变参数求最大值
ObjectUtils.compare(a, b, true);                // 第三个参数:null 是否视为更小
ObjectUtils.allNotNull(a, b, c);
ObjectUtils.anyNotNull(a, b, c);
ObjectUtils.identityToString(obj);              // 形如 Foo@1a2b3c

// ===== ArrayUtils =====
int[] arr = {1, 2, 3};
ArrayUtils.isEmpty(arr);
ArrayUtils.contains(arr, 2);                    // true
ArrayUtils.add(arr, 4);                         // 返回新数组 {1,2,3,4}
ArrayUtils.addAll(arr, new int[]{4, 5});
ArrayUtils.remove(arr, 1);                      // 移除索引 1 → {1,3}
ArrayUtils.reverse(arr);                        // 原地反转
ArrayUtils.toObject(arr);                       // int[] → Integer[](装箱)
ArrayUtils.toPrimitive(new Integer[]{1, 2});    // Integer[] → int[](拆箱)
ArrayUtils.indexOf(arr, 2);
ArrayUtils.subarray(arr, 0, 2);

// 泛型数组同样适用
String[] strs = ArrayUtils.toArray("a", "b");

// ===== BooleanUtils =====
BooleanUtils.toBoolean("yes");       // true(支持 yes/on/true/y/t/1)
BooleanUtils.toBoolean("Y");         // true
BooleanUtils.toBoolean(1);           // true
BooleanUtils.toBooleanObject("on");  // Boolean.TRUE
BooleanUtils.toBooleanObject("maybe"); // null,无法识别
BooleanUtils.isTrue(boolObj);        // null 安全的 == true
BooleanUtils.isNotTrue(boolObj);     // null 或 false 都为 true
BooleanUtils.negate(Boolean.TRUE);   // false
BooleanUtils.xor(true, false, true); // false,异或
BooleanUtils.toInteger(true);        // 1