JAVA:别再滥用 != null 判空了

一、前言

  为了防止项目中出现空指针异常,我们经常在代码中使用!= null判断。当然这样写也能改变问题,可是不管是什么数据类型,都是都这样子写,可是真的不好看啊。今天来介绍几个便捷的方式

二、如何解决

1.首先了解一下,是判断什么类型的不为空呢,是字符串,还是对象,还是集合呢?

三、代码示例

  StringUtils 是 Apache Commons Lang 库中的一个工具类,用于处理字符串相关的操作。它提供了许多静态方法,如判断字符串是否为空、拼接字符串、去除字符串两端的空格等。

    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = null;

        // 判断字符串是否为空或null
        boolean isEmpty = StringUtils.isEmpty(str2); // true

        boolean isNotEmpty = StringUtils.isNotEmpty(str1); // true

        System.out.println("isEmpty======: " + isEmpty);

        System.out.println("isNotEmpty======: " + isNotEmpty);

        // 拼接字符串
        String concatenated = StringUtils.join(new String[]{"Hello", "World"}, " "); // "Hello World"

        // 去除字符串两端的空格
        String trimmed = StringUtils.trim("   Hello World   "); // "Hello World"

        System.out.println("concatenated=======: " + concatenated);

        System.out.println("trimmed=====: " + trimmed);
    }

  ObjectUtils 也是 Apache Commons Lang 库中的一个工具类,用于处理对象相关的操作。它提供了许多静态方法,如判断对象是否为空、比较对象、获取对象的默认值等。

 public static void main(String[] args) {
        Object obj1 = "Hello";
        Object obj2 = null;

        // 判断对象是否为空(null)
        boolean isNull = ObjectUtils.isEmpty(obj2); // true

        boolean isNotNull = ObjectUtils.isNotEmpty(obj1); // true

        System.out.println("isNull=======: " + isNull);
        System.out.println("isNotNull=========: " + isNotNull);

        // 获取对象的默认值
        Object defaultIfNull = ObjectUtils.defaultIfNull(obj2, "Default");// "Default"
        System.out.println("defaultValue========: " + defaultIfNull);

    }

  CollectionUtils 是 Apache Commons Collections 库中的一个工具类,用于处理集合(List、Set等)相关的操作。它提供了许多静态方法,如判断集合是否为空、集合的交集、并集、差集等。

四、总结

1.使用StringUtils.isEmpty和StringUtils.isNotEmpty来优雅地判断字符串是否为空或null。

2.使用ObjectUtils.isEmpty和ObjectUtils.isNotEmpty来检查对象是否为null(它们不检查非字符串对象的“空”状态)

3.使用CollectionUtils.isEmpty结合对集合本身的null检查来判断集合是否为空。

public void addActivityScore(Long userId, ActivityScoreBo activityScore) { if (userId == null) { return; } // 1. 计算活跃度(正为加活跃,负为减活跃) String field; int score = 0; if (activityScore.getPath() != null) { field = "path_" + activityScore.getPath(); score = 1; } else if (activityScore.getArticleId() != null) { field = activityScore.getArticleId() + "_"; if (activityScore.getPraise() != null) { field += "praise"; score = BooleanUtils.isTrue(activityScore.getPraise()) ? 2 : -2; } else if (activityScore.getCollect() != null) { field += "collect"; score = BooleanUtils.isTrue(activityScore.getCollect()) ? 2 : -2; } else if (activityScore.getRate() != null) { // 评论回复 field += "rate"; score = BooleanUtils.isTrue(activityScore.getRate()) ? 3 : -3; } else if (BooleanUtils.isTrue(activityScore.getPublishArticle())) { // 发布文章 field += "publish"; score += 10; } } else if (activityScore.getFollowedUserId() != null) { field = activityScore.getFollowedUserId() + "_follow"; score = BooleanUtils.isTrue(activityScore.getFollow()) ? 2 : -2; } else { return; } final String todayRankKey = todayRankKey(); final String monthRankKey = monthRankKey(); // 2. 幂等,断之前是否有更新过相关的活跃度信息 final String userActionKey = ACTIVITY_SCORE_KEY + userId + DateUtil.format(DateTimeFormatter.ofPattern("yyyyMMdd"), System.currentTimeMillis()); Integer ans = RedisClient.hGet(userActionKey, field, Integer.class); if (ans == null) { // 2.1 之前没有加分记录,执行具体的加分 if (score > 0) { // 记录加分记录 RedisClient.hSet(userActionKey, field, score); // 个人用户的操作记录,保存一个月的有效期,方便用户查询自己最近31天的活跃情况 RedisClient.expire(userActionKey, 31 * DateUtil.ONE_DAY_SECONDS); // 更新当天和当月的活跃度排行榜 Double newAns = RedisClient.zIncrBy(todayRankKey, String.valueOf(userId), score); RedisClient.zIncrBy(monthRankKey, String.valueOf(userId), score); if (log.isDebugEnabled()) { log.info("活跃度更新加分! key#field = {}#{}, add = {}, newScore = {}", todayRankKey, userId, score, newAns); } if (newAns <= score) { // 日活跃榜单,保存31天;月活跃榜单,保存1年 RedisClient.expire(todayRankKey, 31 * DateUtil.ONE_DAY_SECONDS); RedisClient.expire(monthRankKey, 12 * DateUtil.ONE_MONTH_SECONDS); } } } else if (ans > 0) { // 2.2 之前已经加过分,因此这次减分可以执行 if (score < 0) { Boolean oldHave = RedisClient.hDel(userActionKey, field); if (BooleanUtils.isTrue(oldHave)) { Double newAns = RedisClient.zIncrBy(todayRankKey, String.valueOf(userId), score); RedisClient.zIncrBy(monthRankKey, String.valueOf(userId), score); if (log.isDebugEnabled()) { log.info("活跃度更新减分! key#field = {}#{}, add = {}, newScore = {}", todayRankKey, userId, score, newAns); } } } } }
03-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗的狍子007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值