在 Java 8 之前,任何访问对象方法或属性的调用都可能导致 NullPointerException:
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();
这种多层嵌套,如果其中一个为NULL,就会触发NullPointerException.
为此,必须进行判断.
if (user != null) {
Address address = user.getAddress();
if (address != null) {
Country country = address.getCountry();
if (country != null) {
String isocode = country.getIsocode();
if (isocode != null) {
isocode = isocode.toUpperCase();
}
}
}
}
创建OPTIONAL实例
@Test(expected = NoSuchElementException.class)
public void whenCreateEmptyOptional_thenNull() {
Optional<User> emptyOpt = Optional.empty();
emptyOpt.get();
}
毫不奇怪,尝试访问 emptyOpt 变量的值会导致 NoSuchElementException。
你可以使用 of() 和 ofNullable() 方法创建包含值的 Optional。两个方法的不同之处在于如果你把 null 值作为参数传递进去,of() 方法会抛出 NullPointerException:
@Test(expected = NullPointerException.class)
public void whenCreateOfEmptyOptional_thenNullPointerException() {
Optional<User> opt = Optional.of(user);
}
你看,我们并没有完全摆脱 NullPointerException。因此,你应该明确对象不为 null 的时候使用 of()。
如果对象即可能是 null 也可能是非 null,你就应该使用 ofNullable() 方法:
Optional<User> opt = Optional.ofNullable(user);
访问 Optional 对象的值
从 Optional 实例中取回实际值对象的方法之一是使用 get() 方法:
@Test
public void whenCreateOfNullableOptional_thenOk() {
String name = "John";
Optional<String> opt = Optional.ofNullable(name);
assertEquals("John", opt.get());
}
不过,你看到了,这个方法会在值为 null 的时候抛出异常。要避免异常,你可以选择首先验证是否有值:
@Test
publ