ObjectUtils工具类常用方法详解

后端 潘老师 6个月前 (11-17) 173 ℃ (0) 扫码查看

本文主要讲解关于ObjectUtils工具类常用方法总结相关内容,并结合代码案例详细解释,让我们来一起学习下吧!

常用方法

1、isEmpty(Object obj)

检查对象是否为空。如果对象为null或者为空字符串、空数组、空Collection、空Map或者空Iterator,则返回true;否则返回false。

String str = "";
boolean empty = ObjectUtils.isEmpty(str); // true

2、isNotEmpty(Object obj)

检查对象是否非空。如果对象不为null且不为空字符串、空数组、空Collection、空Map或者空Iterator,则返回true;否则返回false。

String str = "Hello";
boolean notEmpty = ObjectUtils.isNotEmpty(str); // true

3、equals(Object object1, Object object2)

比较两个对象是否相等,可以处理null值,避免了NullPointerException的出现。

String str1 = "Hello";
String str2 = "Hello";
boolean equals = ObjectUtils.equals(str1, str2); // true

4、hashCode(Object obj)

计算对象的哈希码,可以处理null值。

String str = "Hello";
int hashCode = ObjectUtils.hashCode(str); // 69609650

5、toString(Object obj)

将对象转换为字符串。如果对象为空,则返回字符串”null”。

int num = 123; 
String str = ObjectUtils.toString(num); // "123"

6、defaultIfNull(T object, T defaultValue)

如果对象为空,则返回默认值。

String str = null;
String defaultStr = "default";
String result = ObjectUtils.defaultIfNull(str, defaultStr); // "default"

7、allNotNull(Object… objects)

检查多个对象是否都不为空。如果所有对象都不为空,则返回true;否则返回false。

String str1 = "Hello";
String str2 = "World";
boolean allNotNull = ObjectUtils.allNotNull(str1, str2); // true

8、anyNotNull(Object… objects)

检查多个对象中是否至少有一个不为空。如果至少有一个对象不为空,则返回true;否则返回false。

String str1 = "Hello";
String str2 = null;
boolean anyNotNull = ObjectUtils.anyNotNull(str1, str2); // true

9、compare(Comparable c1, Comparable c2)

比较两个可比较的对象的大小。可以处理null值。如果c1小于c2,则返回负数;如果c1等于c2,则返回0;如果c1大于c2,则返回正数。

Integer num1 = 123;
Integer num2 = 456;
int result = ObjectUtils.compare(num1, num2); // -1

10、min(Comparable… values)

返回一组可比较对象中的最小值,可以处理null值。

Integer num1 = 123;
Integer num2 = 456;
Integer min = ObjectUtils.min(num1, num2); // 123

11、max(Comparable… values)

返回一组可比较对象中的最大值,可以处理null值。

Integer num1 = 123;
Integer num2 = 456;
Integer max = ObjectUtils.max(num1, num2); // 456

12、clone(Object obj)

克隆一个对象。如果对象实现了Cloneable接口,则调用其clone()方法进行克隆;否则返回null。

Person person = new Person("John", 30);
Person clone = ObjectUtils.clone(person); // 返回person的克隆对象

项目中运用案例

登陆时判断密码和账号是否正确


@PostMapping("/login")
public Result login(@RequestBody Account account) {
    if (ObjectUtil.isEmpty(account.getUsername()) || ObjectUtil.isEmpty(account.getPassword())
            || ObjectUtil.isEmpty(account.getRole())) {
        return Result.error(ResultCodeEnum.PARAM_LOST_ERROR);
    }
    if (RoleEnum.ADMIN.name().equals(account.getRole())) {
        account = adminService.login(account);
    }
    return Result.success(account);
}

以上就是关于ObjectUtils工具类常用方法详解相关的全部内容,希望对你有帮助。欢迎持续关注潘子夜个人博客,学习愉快哦!


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/11348.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】