Java防止NPE技巧

98 阅读1分钟

1. equals()方法常量在前

  • 如果一个对象又可能为Null那么尽量不要直接使用他的方法
private Boolean isKong(String str){
	//str为空会出现NPE
	return str.equals("kong"); //×
    return "kong".equals;      //√
}

2. 初始化赋默认值

  • 对象初始化的时候赋默认值
String str = null; //X
String str = "";   //√

3. StringUtils类

  • StringUtils.isEmpty()

      //StringUtils.java源码
      public static boolean isEmpty(fina CharSequence cs){
          return cs == null || cs.length() == 0;
      }
      //isEmpty()为空或长度为0就返回true判为空
    
  • StringUtils.isBlank()

     //StringUtils.java源码
     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))){
                 return true;
             }
         }
         return true;
     }
     //isBlank()在isEmpty()的基础上多了个判断,空格换行等特殊字符也会返回true判为空
    
  • StringUtils.equals()

    //StringUtils.java源码
    public static boolean equals(final CharSequence cs1,final CharSequence cs2){
    	//==:当为基本类型时==比较的是他们的值,当为引用类型时==比较的是他们的地址
        //若为同一引用或值相等的基本类型,直接返回true
        if(cs1 == cs2){
            return true;
        }
    	//任一方为空直接返回false
        if(cs1 == null || cs2 == null){
            return false;
        }
        //长度不同直接返回false
        //空格也有长度
        if(cs1.length() != cs2.length()){
            return false;
        }
        //a instanceof b,其中a为一个对象,b为一个类或接口;判断a是否是b的实现类,直接或间接子类
        //其中equals()来自Object.java ==> equals(Object obj){return (this == obj);};
        if(cs1 instanceof String && cs2 instanceof String){
            return cs1.equals(cs2);
        }
        //regionMatches()这个源码有点长,有兴趣可以自己研究下
        return CharSequenceUtils.regionMatches(cs1,false,0,cs2,0,cs1.length());
    }
    
  1. 常见判断方法

    • contains()
    • indexOf()
    • isEmpty()
    • containsKey()
    • ContainsValue(),
    • hasNext()等判断空。
  2. 返回空集合

 public List<String> getStr(){
     List<String> sstr = null;
     //TODO
     return (sstr == null) ? new ArrayList() :sstr;
 } 
  1. try/catch捕获

  2. assert关键字

  • 断言检查程序的安全性,不符合就报异常,符合就继续
assert (str !=Null) :"str is null";
  1. Optional(JDK8 新特性,用来解决空指针异常)
    • 一个可以为null的容器对象
    • isPresent()存在返回true;调用get()返回该对象
    • int hashCode()返回存在值的哈希码,不存在返回0
    • ofNullable(T value)非空返回Optional描述的指定值,否则返回空的Optional。
    • T orElse(T other)存在返回该值,否则返回other