java8 Optional.orElseThrow()

    @Test
    void testOptional() {
        User user = getUser();
        System.out.println(user);

        //isPresent()如果值存在则方法会返回true,否则返回 false。
        //true
        User user2 = new User();
        boolean present = Optional.ofNullable(user2).isPresent();
        System.out.println(present);

        //true
        List list = Collections.EMPTY_LIST;
        boolean present1 = Optional.ofNullable(list).isPresent();
        System.out.println(present1);

        String str = null;
        boolean present2 = Optional.ofNullable(str).isPresent();
        System.out.println(present2);

    }

    /**
     * 如果对象不为null,返回该对象,否则抛异常
     * @return
     */
    private User getUser(){
        User user = new User();

        //orElseThrow()如果存在该值,返回包含的值,否则抛出由 Supplier 继承的异常
        //除了null,其他空类型的数据都属于存在该值
        return Optional.ofNullable(user).orElseThrow(() -> new NotFoundException("记录不存在"));
    }

 

你可能感兴趣的:(java8)