Java在8的版本,新增了Optional和lambda表達式,使得平常開發中對於NullPointException的判斷變的優雅。this
如今來個例子看看在Optional以前對空的判斷。spa
@Test public void testOpt() { User u = new User(); u.setName("hy"); if (u != null && u.getName() != null) { System.out.println(u.getName()); } }
public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
若是層級更深的話,那就更難看一些...code
看看經過Optional改造後的版本blog
@Test(expected = MyException.class) public void testOpt() { User s = new User(); s = null; // s.setName(null); Optional<User> opt = Optional.ofNullable(s); String name = opt.map(user -> user.getName()).orElseThrow(()-> new MyException("異常")); //Assert.assertEquals("hy", name); System.out.println(name); }
public class MyException extends RuntimeException { MyException() { } MyException(String mgs) { super(mgs); } }
沒有了惱人的if判空,變的優雅不少,其實lambda表達式使以前不少很繁瑣的表達變的優雅,之後也會把更多的優雅用法貼到這裏備忘。開發