java如何避免NullPointerException(空指针异常,NPE)

本文将简单的介绍nep以及如何避免npe


1.npe简介

空指针异常(NullPointerException)意思是指java中的异常类。当应用程序试图在需要对象的地方使用null时,抛出该异常。

这种情况包括:

  • 调用 null 对象的实例方法。

  • 访问或修改 null 对象的字段。

  • 将 null 作为一个数组,获得其长度。

  • 将 null 作为一个数组,访问或修改其时间片。

  • 将 null 作为 Throwable 值抛出。

简单点说 对象未初始化,因此它们指向空引用 

Null 和真实对象之间没有区别 所以,从编译器的角度来看,没有错。Null 属于真实对象

但是,一旦我们运行这个程序,它将失败并出现 NullPointerException: 

 万恶之源啊!!!!!!!   如图

 72e79b18cff14515ab96fb622d386680.png

2.如何避免npe

就是在访问对象之前 要谨慎!!  始终检查它是否为null,包括方法参数、返回值 

比如  ↓↓↓↓↓↓↓↓

User user = userManager.getById(userId);
if (null == user) {
    log.warn("用户不存在 用户编号:{}",userId);
    return;
}
//业务处理

常用的对象判断  我们一般使用

if (Objects.isNull(user)){
    // 异常处理
    }
if (null == user){
     // 异常处理
    }

常用的字符串判空  我们一般使用

org.apache.commons.lang3 他是一个强大的java类库 提供了处理字符串、日期、集合、文件等等大量实用的工具类 这里只讲解字符串判空

StringUtils.isEmpty()

判断是否为null 空串

StringUtils.isEmpty(null) = true;

StringUtils.isEmpty("") = true;

StringUtils.isEmpty(" ") = false;

StringUtils.isEmpty("test") = false;

StringUtils.isEmpty(" test ") = false

/
 *
 * <p>NOTE: This method changed in Lang version 2.0.
 * It no longer trims the CharSequence.
 * That functionality is available in isBlank().</p>
 *
 * @param cs  the CharSequence to check, may be null
 * @return {@code true} if the CharSequence is empty or null
 * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
 */
public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}

StringUtils.isNotEmpty()

相当于不为空 , = !isEmpty()

public static boolean isNotEmpty(final CharSequence cs) {
        return !isEmpty(cs);
    }

StringUtils.isAnyEmpty()

是否有一个为空,只有一个为空,就为true.

StringUtils.isAnyEmpty(null) = true
StringUtils.isAnyEmpty(null, “test”) = true
StringUtils.isAnyEmpty("", “test”) = true
StringUtils.isAnyEmpty(“test”, “”) = true
StringUtils.isAnyEmpty(" test", null) = true
StringUtils.isAnyEmpty(" ", “test”) = false
StringUtils.isAnyEmpty(“test”, “test”) = false
/
 * @param css  the CharSequences to check, may be null or empty
 * @return {@code true} if any of the CharSequences are empty or null
 * @since 3.2
 */
public static boolean isAnyEmpty(final CharSequence... css) {
  if (ArrayUtils.isEmpty(css)) {
    return true;
  }
  for (final CharSequence cs : css){
    if (isEmpty(cs)) {
      return true;
    }
  }
  return false;
}

StringUtils.isNoneEmpty()

相当于!isAnyEmpty(css) , 必须所有的值都不为空才返回true

/**
     * <p>Checks if none of the CharSequences are empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isNoneEmpty((String) null)    = false
     * StringUtils.isNoneEmpty((String[]) null)  = true
     * StringUtils.isNoneEmpty(null, "foo")      = false
     * StringUtils.isNoneEmpty("", "bar")        = false
     * StringUtils.isNoneEmpty("bob", "")        = false
     * StringUtils.isNoneEmpty("  bob  ", null)  = false
     * StringUtils.isNoneEmpty(new String[] {})  = true
     * StringUtils.isNoneEmpty(new String[]{""}) = false
     * StringUtils.isNoneEmpty(" ", "bar")       = true
     * StringUtils.isNoneEmpty("foo", "bar")     = true
     * </pre>
     *
     * @param css  the CharSequences to check, may be null or empty
     * @return {@code true} if none of the CharSequences are empty or null
     * @since 3.2
     */
    public static boolean isNoneEmpty(final CharSequence... css) {
      return !isAnyEmpty(css);
    }

StringUtils.isBlank()

是否为空值(空格或者空值)

StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank(“test”) = false
StringUtils.isBlank(" test") = false

/
 * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
 * @param cs  the CharSequence to check, may be null
 * @return {@code true} if the CharSequence is null, empty or whitespace
 * @since 2.0
 * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
 */
public static boolean isBlank(final CharSequence cs) {
    int strLen;
    if (cs == null || (strLen = cs.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (Character.isWhitespace(cs.charAt(i)) == false) {
            return false;
        }
    }
    return true;
}

StringUtils.isNotBlank()

是否真的不为空,不是空格或者空值 ,相当于!isBlank();

public static boolean isNotBlank(final CharSequence cs) {
        return !isBlank(cs);
    }

StringUtils.isAnyBlank()

是否包含任何空值(包含空格或空值)

StringUtils.isAnyBlank(null) = true
StringUtils.isAnyBlank(null, “test”) = true
StringUtils.isAnyBlank(null, null) = true
StringUtils.isAnyBlank("", “test”) = true
StringUtils.isAnyBlank(“test”, “”) = true
StringUtils.isAnyBlank(" test", null) = true
StringUtils.isAnyBlank(" ", “test”) = true
StringUtils.isAnyBlank(“test”, “test”) = false
/
 * <p>Checks if any one of the CharSequences are blank ("") or null and not whitespace only..</p>
 * @param css  the CharSequences to check, may be null or empty
 * @return {@code true} if any of the CharSequences are blank or null or whitespace only
 * @since 3.2
 */
public static boolean isAnyBlank(final CharSequence... css) {
  if (ArrayUtils.isEmpty(css)) {
    return true;
  }
  for (final CharSequence cs : css){
    if (isBlank(cs)) {
      return true;
    }
  }
  return false;
}

StringUtils.isNoneBlank()

是否全部都不包含空值或空格

StringUtils.isNoneBlank(null) = false
StringUtils.isNoneBlank(null, “test”) = false
StringUtils.isNoneBlank(null, null) = false
StringUtils.isNoneBlank("", “test”) = false
StringUtils.isNoneBlank(“test”, “”) = false
StringUtils.isNoneBlank(" test", null) = false
StringUtils.isNoneBlank(" ", “test”) = false
StringUtils.isNoneBlank(“test”, “test”) = true
/
 * <p>Checks if none of the CharSequences are blank ("") or null and whitespace only..</p>
 * @param css  the CharSequences to check, may be null or empty
 * @return {@code true} if none of the CharSequences are blank or null or whitespace only
 * @since 3.2
 */
public static boolean isNoneBlank(final CharSequence... css) {
  return !isAnyBlank(css);
}

===================================================================

.toString()

除了这些在引用前的判断之外 还有容易出现空指针的地方 ↓↓↓↓↓↓↓↓

.toString()  相信大家使用过  但是如果你引用的时候  属性为空  那么npe 就又来了 除了使用上面的判空 还可以怎么避免呢   那就是

String.valueOf()
/**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

他会有判空的处理  如果为空会返回 字符串"null" 这样就不会有万恶的npe了

又或者    obj + ""    加个空字符串   

===========================================================

CollUtil.isEmpty()

集合判空的话  我还是喜欢

hutool的CollUtil.isEmpty()
/**
	 * 集合是否为空
	 * 
	 * @param collection 集合
	 * @return 是否为空
	 */
	public static boolean isEmpty(Collection<?> collection) {
		return collection == null || collection.isEmpty();
	}

================================================================

Optional

其实JDK8以上版本提供了Optional类,它是一个容器对象,可用于包装可能为null的值。这里就不细说了   因为使用的人真的很少  有兴趣可以下来查一下相关资料

 

扩展:JSONException

json解析异常   问题的起源是 有一天测试过来说  有一个问题  就是......
大概意思就是去调用三方的接口的时候   页面提示JSONException 

带着问题看代码  发现是一个已经走了的一个开发编写的 ↓↓↓↓↓↓↓↓

if (StringUtils.isNotBlank(result) && "error".equals(result)){
            return Result.error("请重试");
        }
        JSONObject jsonObject = JSON.parseObject(result);

这样真的可以确认三方返回的报文是正确的吗?  

答案肯定是不行  查看日志   三方返回的是非json格式数据  具体就不展开说了

所以该怎么办呢?  怎么做比较好呢?

当即封装了一个 

public static boolean isJsonString(String jsonString) {
        try {
            com.alibaba.fastjson2.JSONObject.parseObject(jsonString);
            return true;
        } catch (JSONException e) {
            log.error("非json格式数据");
            return false;
        }
    }
if (StringUtils.isNotBlank(result) && "error".equals(result)){
            return Result.error("请重试");
        }
if (!isJsonString(result)) {
                return Result.error("请求报文格式有误");
            }

JSONObject jsonObject = JSON.parseObject(result);

这样就完美了! 你觉得呢 ?

如果有更好的办法  欢迎大家评论。

 

  • 40
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

宇先生?。

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

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

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

打赏作者

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

抵扣说明:

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

余额充值