Java 8 方法引用:提供能够提供参数化结果的供应商
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22917138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 method references: provide a Supplier capable of supplying a parameterized result
提问by mdo
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?
有没有办法创建一个供应商来传递我的参数值?
采纳答案by Louis Wasserman
Sure. orElseThrow(() -> new MyException(someArgument))
.
当然。 orElseThrow(() -> new MyException(someArgument))
.
回答by Manu
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
看来您只能从方法中抛出 RuntimeException orElseThrow
。否则你会收到类似的错误信息 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.
更新:- 这是旧版本 JDK 的问题。我在最新版本中没有看到这个问题。
回答by Ashish Pushp
optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));