apache的对象工具类ObjectUtils

发布时间 2023-11-29 09:09:07作者: 残城碎梦

org.apache.commons.lang3.ObjectUtils主要是Apache提供的对对象进行操作的工具类。它会使代码变得更加优雅。

判断对象是否为空

boolean isEmpty = ObjectUtils.isEmpty(new Person());
//输出:false
boolean isEmpty = ObjectUtils.isEmpty(null);
//输出:true

检查元素是否为空

//检查所有元素是否都不为空
boolean isAllNotNull = ObjectUtils.allNotNull(new Person(), null);
//输出:false
//检查所有元素是否至少有一个非空
boolean isAnyNotNull = ObjectUtils.anyNotNull(new Person(), null);
//输出:true

拷贝对象(引用拷贝)

引用拷贝也就是我们常用的对象赋值,这种方式不会生成新的对象,只会在原对象上增加了一个新的对象引用,两个引用指向的对象还是是同一个。

Person p = new Person();
p.setName("张三");
//引用拷贝,两个引用指向的还是同一个对象
Person newP = ObjectUtils.cloneIfPossible(p);
System.out.println(newP.getName());
//输出:张三

找非空对象

//如果对象为空,返回默认值
Person p2 = new Person();
p2.setName("李四");
Person newP2 = ObjectUtils.defaultIfNull(null, p2);
System.out.println(newP2.getName());
//输出:李四
//返回对象列表中第一个不为空的对象
Person p1 = new Person();
p1.setName("李四");
Person newP1 = ObjectUtils.firstNonNull(null, p1, null);
System.out.println(newP1.getName());
//输出:李四

对象比较大小

//比较两数字,null最小
int compare = ObjectUtils.compare(10, null);
//输出:1
//比较两数字,null最大
int compare = ObjectUtils.compare(10, null, true);
//输出:-1
//取最大值,null为最小
int max = ObjectUtils.max(10, null);
//输出:10

将参数转换为常量

final int num = ObjectUtils.CONST(12);
//输出:12