有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过使用try-catch避免了无休止的空/空检查

假设我想访问

productList.get(0).getCustomerList().get(0).getAddressList().get(0).getRegion.getCode()

在每个级别,我都需要检查空列表或空列表。数据结构非常复杂,重构可能是一种选择,但也可能太复杂或不可能

由此产生的代码将是:

if(productList != null 
   && !productList.isEmpty() 
   && productList.get(0).getCustomerList().get(0) != null 
   && ...){
  return productList.get(0).getCustomerList().get(0).getAddressList(0).getRegion.getCode();
}

由此产生的代码丑陋、冗长,没有任何真正的业务逻辑,而且很难阅读。有什么聪明的方法可以避免这种情况吗?是否可以接受这样做:

try{
  return productList.get(0).getCustomerList().get(0).getAddressList(0).getRegion.getCode();
} catch(NullPointerException | IndexOutOfBoundException e){
  return null;
}

共 (1) 个答案

  1. # 1 楼答案

    下面是使用Java8可选的另一个建议

    Predicate<List> hasElement = list -> list != null && !list.isEmpty();
    
    String code = Optional.ofNullable(productList)
    .filter(hasElement).map(p -> p.get(0).getCustomerList())
    .filter(hasElement).map(c -> c.get(0).getAddressList())
    .filter(hasElement).map(a -> a.get(0).getRegion())
    .map(Region::getCode)
    .orElse(null);