什么是空指针?
当一个变量的值为 null 时,在 Java 里面表示一个不存在的空对象,没有实际内容,没有给它分配内存,null 也是对象成员变量的默认值。
所以,一个对象如果没有进行初始化操作,这时候,如果你调用这个对象的方法或者变量,就会出现空指针异常。
如下面示例会发生空指针异常:
Object object = null;
String string = object.toString();
案例一:
public String getUserIdByMobile(String mobile) {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
req.setMobile(mobile);
OapiV2UserGetbymobileResponse rsp = null;
try {
rsp = client.execute(req, DingAccessToken.getAccessToken());
} catch (Exception e) {
throw new RuntimeException(e);
}
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = null;
String userId = null;
try {
jsonNode = objectMapper.readTree(rsp.getBody());
if (jsonNode != null && jsonNode.get("result") != null && jsonNode.get("result").get("userid") != null) {
userId = jsonNode.get("result").get("userid").asText();
}
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return userId;
}
17行报空指针异常,注意如果不处理空指针异常,程序会报错,无法正常执行
需要注意空指针异常是指去调用方法的主体为null,一个不为空的对象去调用方法get一个null的值时,是不存在空指针异常的,会返回null
另外一点:关于异常的处理,异常被捕获抛出后,程序可以正常继续执行,如果异常没有被处理,程序会报错
如何避免空指针?
1、字符串比较,常量放前面
if(SUCCESS.equals(status)){
}
2、初始化默认值
User user = new User();
String name = StringUtils.EMPTY;
3、返回空集合
public List getUserList(){
List list = userMapper.gerUserList();
return list == null ? new ArrayList() : list;
}
以下案例:对潜在空指针的处理