目录
1:空指针问题
2:解决方法
第一种方式:
第二种方式:
第三种方式:
第四种方式:
1:空指针问题
Java是没有指针的,所以我们常说"Java 指针"就是指"Java 的引用"。空指针就是空引用,Java空指针异常就是引用本身为空,但却调用了方法,这个时候就会出现空指针异常
public class demo {
public static void main(String[] args) {
Address address = new Address();
User user = new User("xia", 12, address);
String cityName = user.getAddress().getCity().trim();
System.out.println(cityName);
}
}
Address:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Address {
private String city;
private String address;
}
User:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private Integer age;
private Address address;
}
2:解决方法
第一种方式:
使用if 来进行非空判断
/**
使用if 条件判断,但是这种写法不优美
*/
public class demo {
public static void main(String[] args) {
Address address = new Address();
User user = new User("xia", 12, address);
if (user != null){
Address userAddress = user.getAddress();
if (userAddress != null) {
String city = address.getCity();
if (city != null && !"".equals(city)){
System.out.println(user.getAddress().getCity().trim());
}
}
}
}
}
第二种方式:
使用Optional.ofNuallable 来进行处理
public class demo {
public static void main(String[] args) {
Address address = new Address();
User user = new User("xia", 12, address);
String ored = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.map(String::trim)
.orElse("default");
System.out.println(ored);
}
}
第三种方式:
使用Assert 断言
public class demo {
public static void main(String[] args) {
Address address = new Address();
User user = new User("xia", 12, address);
getUserCity(user);
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
getUserCity(null);
}
public static void getUserCity(User user){
Assert.notNull(user,"user is null");
Address address = user.getAddress();
Assert.notNull(address,"address is null");
String city = address.getCity();
System.out.println(city);
}
}
第四种方式:
使用@Nullable 注解(代码会有提示)
public class demo {
public static void printString(@Nullable String str){
System.out.println(str.toString());
}
@Nullable
public static String getString(){
return null;
}
public static void main(String[] args) {
Address address = new Address();
String str = null;
printString(str);
getString().toString();
User user = new User();
System.out.println(user.getAddress().getCity());
}
}
提示: