工作中如何避免 Java NPE

2023-07-14  本文已影响0人  天之骄子_7541

Java NPE是一个非常令人头疼的问题,在这里简单记录下我们在工作中应该如何避免。
部分内容摘抄自网络,部分来自工作中的心得体会。

1.使用obj.doSomething()时记得判断obj != null
01.从Map集合中get出来的对象使用前先判空
02.对集合进行java8 stream前先判空
03.调用第三方接口返回的数据使用前先判空
04.上层方法传递的集合参数,使用前先判空
05.java8 stream List转Map时,需要先过滤掉key为空的对象
06.java8 stream List转Map时,要考虑key冲突时的情况,例如冲突时覆盖

// java8 stream List转Map
@Test
public void test_listToMap(){
    List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, null));
    Map<Integer, List<Integer>> collect = list.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.groupingBy(p -> p));
    System.out.println(collect);
}

//java8 stream List转Map时,要考虑key冲突
@Test
public void test_listToMap2() {
    List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 6, 2));
    Map<Integer, Integer> collect = list.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(p -> p, Function.identity(), (key1, key2) -> key2));
    System.out.println(collect);
}

2.判断对象是否相等时,使用Objects.equals(objectA,objectB)方法,注意这里传入的对象必须是同一类型
判断失败的情况:
01.Integer类型 和Long类型的数字进行了比较
02.Timestamp类型和Date类型比较

//反例
@Test
public void test_objects_equals() {
    Integer num1 = 1;
    long num2 = 2L;
    System.out.println(Objects.equals(num1, num2));
    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    Date date = new Date(timestamp.getTime());
    System.out.println(Objects.equals(timestamp, date));
}

3.自动拆箱导致的空指针
建议包装类型的数字在使用时先转换为基本类型,值为null时给默认值,然后再进行加减乘除和==比较

// 反例
@Test
public void test_integer_npe(){
    Integer num1 = null;
    Integer num2 = 2;
    System.out.println(num1 + num2);
}

// 正例
@Test
public void test_integer_npe(){
    Integer num1 = null;
    Integer num2 = 2;
    int n1 = num1 == null ? 0 : num1;
    int n2 = num2 == null ? 0 : num2;
    System.out.println(n1 + n2);
}

4.检查字符串
建议使用commons-lang3包下的StringUtils的工具类

@Test
public void test_string_is_empty() {
    String str1 = null;
    String str2 = "TEST";
    System.out.println(StringUtils.isEmpty(str1));
    System.out.println(Objects.equals(str1,str2));
}

5.检查集合为空
建议使用commons-collections4包下的CollectionUtils方法

6.返回集合为空时,应返回空集合而不是null
建议返回Collections.emptyList()

上一篇 下一篇

猜你喜欢

热点阅读