Java 8 method references: provide a Supplier capab

2019-01-10 05:17发布

问题:

I'd like to use

java.util.Optional.orElseThrow()

with an Exception type that asks for a constructor parameter. Something like this:

orElseThrow(MyException::new(someArgument)) // obviously NOT working

Is there a way to create a Supplier that passes my argument value in?

回答1:

Sure. orElseThrow(() -> new MyException(someArgument)).



回答2:

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException



回答3:

optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));