不会报空指针的N种情况

322 阅读1分钟

兄弟们善于总结平时遇到的情况,慢慢积累才能产生质变,本文就总结一下排查问题中经常遇到的一些地方,老是怀疑会NPE,其实下面的情况是不会NPE的

1. 
String string = JSON.toJSONString(null);
System.out.println(string);

2.
@Test
public void test2() throws UnsupportedEncodingException {
    boolean equals = Objects.equals(1, null);
    System.out.println(equals);
}
  1. 这样强转是不会报空指针的,相反toString是会有空指针的

@Test
void testNotExistHashkey1() {
   try{
      String o2 = (String) redisTemplate.opsForHash().get("hashDing", "sexy");
      System.out.println(o2);
   }catch (Exception e){
      System.out.println(e);
   }
}