import com.google.common.base.Optional; public class OptionalTest { public static void main(String[] args) { Student student = new Student(); // student.setName("loli"); String name = student.getName(); // Optional<String> optional = Optional.fromNullable(name); // if (optional.isPresent()) { //// 不为空 // System.out.println(name); // } else { //// 为空走这一条 // System.out.println("null..."); // student.setName("hJosama"); // } // name = null; // optional = Optional.fromNullable(name); // if (!optional.isPresent()) { //// 为空直接走这一条 // } else { //// 不为空 // } if (!Optional.fromNullable(name).isPresent()){ System.out.println("null..."); name="hJosama"; } if (Optional.fromNullable(name).isPresent()){ System.out.println(name); }else { System.out.println("null..."); } } private static class Student { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } }
<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.0.1-jre</version> </dependency>
参考:https://www.cnblogs.com/sungang/archive/2014/04/02/3641164.html