Table of contents
1: Null pointer problem
Java has no pointers, so we often say that "Java pointer" means "Java reference". A null pointer is a null reference. A Java null pointer exception means that the reference itself is null, but a method is called. At this time, a null pointer exception will occur.
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: Solution
The first way:
Use if to make non-null judgment
/**
使用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());
}
}
}
}
}
The second way:
Use Optional.ofNuallable for processing
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);
}
}
The third way:
Use Assert assertion
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);
}
}
The fourth way:
Use @Nullable annotation (the code will be prompted)
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());
}
}
hint: