【发布时间】:2017-08-04 10:37:32
【问题描述】:
下面的方法返回一个 Map。我正在添加一个伪代码,跳过 DAO 如何返回值映射。
public Map<Intger,Integer> getIDsBasingonRanks(){
Map<Integer,Integer> m = new HashMap<>();
// Dao operation fetcing values from DB;
if(dao==null){
//logging some error or info
return null;// In this cases Null Pointer will be thrown. How to handle it ?
}
m.put()// put the values inside the map from DAO
return m;
}
现在我从另一个返回 Map 的类调用 getIDsBasingonRanks() 并从该映射中获取值
Map<Integer,Integer> m2 = getIDsBasingonRanks();
m2.getkey();//Incase the map is null we will have Null Pointer Exception
m2.getValue(); //Incase the map is null we will have Null Pointer Exception
我觉得在 dao=null 条件下处理上述方法的 return 语句很棘手。如何在返回 null 时为方法提供返回以克服空指针,因为我们也无法处理它们。
【问题讨论】:
-
在调用任何成员函数之前检查
m2不是null(m2.getKey()等)。就像您在getIDsBasingonRanks函数中检查dao不是null一样。 -
很酷,回答了这个问题。但是任何其他方式来返回地图,就像字符串返回“”;
-
如果您想要不同类型的错误检测返回,您可以使用
Optional。 -
为什么要在每个获取方法中检查 dao == null ?根据 java 中的设计模式,dao 应该被实例化一次并因此被检查一次。您也可以尝试捕获 NullPointerException 并在 catch 块中处理它。
标签: java