@Test(expected = NoSuchElementException.class) public void whenCreateEmptyOptional_thenNull() { Optional<User> emptyOpt = Optional.empty(); emptyOpt.get();// 没有值 将会抛出异常 } @Test(expected = NullPointerException.class) public void test_of() { User user=null; Optional<User> optional = Optional.of(user); } @Test public void test_ofNuLLAble() { User user=null; Optional<User> optional = Optional.ofNullable(user); optional.orElse(new User()); // 一般不使用 optional.get(); }
详解Java8 Optional类{最全} (2)
内容版权声明:除非注明,否则皆为本站原创文章。