一.发生空指针异常常见情况
1.字符串变量未初始化;
2.接口类型的对象没有用具体的类初始化,比如: List lt;会报错 ,List lt = new ArrayList(); 则不会报错了
3.当一个对象的值为空时,你没有判断为空就引用此对象的其他方法 会报空。
空指针是一个运行异常:由RuntimeException派生出来,是一个运行级别的异常;特别注意需要看这样的运行级别异常是否会导致你的业务逻辑中断
空指针异常发生在对象为空,但是引用这个对象的方法。
例如: String s = null; //对象s为空(null)
int length = s.length();//发生空指针异常 对象为空却去调用方法
二.如何避免空指针
1.声明一个变量时最好给它分配好内存空间,给予赋值;
2.拿该变量与一个值比较时,要么先做好该异常的处理如: if (str == null) { System.out.println("字符为空!"); }
当然也可以将这个值写在前面进行比较的,例如,判断一个String的实例s是否等于“a”,不要写成s.equals("a"),这样写容易抛出NullPointerException,而写成"a".equals(s)就可以避免这个问题。不过对变量先进行判空后再进行操作比较好 ;
3.注意查询的返回值或方法的return 进行非空判断
LeadDay leadDay= leadDayMapper.getLeadDay(map);
if(leadDay==null) return ServerResponse.createByErrorMessage("未查询出数据!");
List<LeadDay> tendList=leadDayMapper.selectLeadDayProvince(map);
if(CollectionUtils.isEmpty(tendList))return ServerResponse.createByErrorMessage("未查询出数据!");
public abstract class CollectionUtils {
/**
* Return {@code true} if the supplied Collection is {@code null} or empty.
* Otherwise, return {@code false}.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(@Nullable Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
}