如何从可选中提取字段参数,或者如果为空则抛出异常?

How to extract a field parameter from optional, or throw exception if null?

String result = service.getResult();

if (result == null) {
    DaoObject obj = crudRepository.findOne(..);
    if (obj != null) {
        result = obj.getContent();
    } else {
        throw NotFoundException();
    }
}

service.process(result);

如果 DaoObjectOptional<DaoObject>,我可以做些什么来使用 java 8 实现与上面相同的效果?

有些东西 .orElseThrow(() -> new NotFoundException());,但是上面的代码在流中看起来如何?

附带问题:我应该使用 () -> new NotFoundException() 还是 NotFoundException::new

你可以这样做:

Optional<DaoObject> obj = crudRepository.findOne(..);
result = obj.orElseThrow(NotFoundException::new).getContent();

Sidequestion: should I use () -> new NotFoundException() or NotFoundException::new?

这只是一个选择问题。两个表达式将执行相同的操作。

你的假设是正确的。 这将导致以下代码:

Optional<DaoObject> obj = crudRepository.findOne(..);

result = obj.orElseThrow(() -> new NotFoundException()).getContent();

或者,如果您愿意,可以拆分语句以使其更具可读性:

DoaObject object = obj.orElseThrow(() -> new NotFoundException());
result = object.getContent();

注意() -> new NotFoundException()NotFoundException::new是完全一样的,所以只是看你觉得哪个更易读了。