如何防止空指针异常

Object resCodeObj = null;


///返回接口response
try {
   String s = String.valueOf(resCodeObj);
   System.out.println(s);
   System.out.println(4444);
   if (!ObjectUtils.isEmpty(s)) {
      Integer resCode = Integer.valueOf(s);
      System.out.println(resCode);

   }else {
      System.out.println(333);
   }
} catch (NumberFormatException e) {
   System.out.println(11);
   e.printStackTrace();
}

System.out.println(22);

总结:

如果resCodeObj为null,

String.valueOf为 "null"

" "和"null" 不能Integer.valueOf,会报空指针异常

s.equal 为 "null"为true  s.equal(null)为false

你可能感兴趣的:(文章)