java8利用optional解决NPE

mac2024-12-03  24

optional

问题:
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();

可能有NPE出现,必须加上判断

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解决
创建Optional实例
Optional.empty()返回一个空的Optional对象Optional.of(user);传入一个非空的参数,返回一个OptionalOptional.ofNullable(user);允许传入的为null,为null创建一个空的Optional对象。
访问Optional对象的值
opt.get();当opt是空的Optional对象时,会返回no such element Exception
返回默认值
orElse:Optional.ofNullable(user).orElse(user2); 如果optional是空的,返回use2;
转换值
map(),对optional内的值调用其返回值,并将返回值封装到Optional中。 @Test public void whenMap_thenOk() { User user = new User("anna@gmail.com", "1234"); String email = Optional.ofNullable(user) .map(u -> u.getEmail()).orElse("default@gmail.com"); assertEquals(email, user.getEmail()); } flatMap()需要函数作为参数,并对值调用这个函数,然后直接返回这个结果; public class User { private String position; public Optional<String> getPosition() { return Optional.ofNullable(position); } //... } @Test public void whenFlatMap_thenOk() { User user = new User("anna@gmail.com", "1234"); user.setPosition("Developer"); String position = Optional.ofNullable(user) .flatMap(u -> u.getPosition()).orElse("default"); assertEquals(position, user.getPosition().get()); }
过滤值
filter()接受一个Predicate参数,返回测试结果为true的值。如果测试结果为false,返回空的Optional。 @Test public void whenFilter_thenOk() { User user = new User("anna@gmail.com", "1234"); Optional<User> result = Optional.ofNullable(user) .filter(u -> u.getEmail() != null && u.getEmail().contains("@")); assertTrue(result.isPresent()); }
Optional类的链式方法
public class User { private Address address; public Optional<Address> getAddress() { return Optional.ofNullable(address); } // ... } public class Address { private Country country; public Optional<Country> getCountry() { return Optional.ofNullable(country); } // ... }

用Optional来代替null判断,进行链式调用

@Test public void whenChaining_thenOk() { User user = new User("anna@gmail.com", "1234"); String result = Optional.ofNullable(user) .flatMap(u -> u.getAddress()) .flatMap(a -> a.getCountry()) .map(c -> c.getIsocode()) .orElse("default"); assertEquals(result, "default"); }
Optional的用法
最好不用做类的字段用于返回结果,然后进行链式调用
最新回复(0)