Java 8 method references: provide a Supplier capable of supplying a parameterized result

你说的曾经没有我的故事 提交于 2019-12-17 08:11:47

问题


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

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.




回答3:


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


来源:https://stackoverflow.com/questions/22917138/java-8-method-references-provide-a-supplier-capable-of-supplying-a-parameterize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!