java - 在 Java 8 中抛出异常时如何在 Optional 中使用构造函数引用传递异常消息
问题描述
我正在寻找一种使用带有 Optional 的构造函数引用来处理带有异常的 null 的方法,我想在其中传递带有异常的自定义消息。
例如,有一项服务提供 getPassword(String userId) 方法来检索密码。它接受一个 String 类型的参数,即 userId。如果系统中不存在userId,则返回null,否则返回密码(String)。现在我正在调用这个方法,如果返回 null,我想抛出 'IllegalArgumentException'。
我知道在 Java 中有很多方法可以做到这一点,但我正在寻找一种使用构造函数引用的可选方法来做到这一点。
//calling getPassword() method to retrieve the password for given userId - "USER_ABC", but there is no such user so null will be returned.
String str = service.getPassword("USER_ABC");
// I want to throw the exception with a custom message if value is null
// Using Lambda I can do it as below.
Optional<String> optStr = Optional.ofNullable(str).orElseThrow(() -> new IllegalArgumentException("Invalid user id!"));
// How to do it using Constructor Reference. How should I pass message ""Invalid user id!" in below code.
Optional<String> optStr = Optional.ofNullable(str).orElseThrow(IllegalArgumentException::New);
解决方案
但我正在寻找一种使用构造函数参考的可选方法。
当您的 Exception 具有无参数构造函数时,您可以:
Optional.ofNullable(null).orElseThrow(RuntimeException::new);
这与以下内容基本相同:
Optional.ofNullable(null).orElseThrow(() -> new RuntimeException());
lambda 的参数和构造函数的参数必须匹配才能使用方法引用。例如:**()** -> new RuntimeException**()**
或**(String s)** -> new RuntimeException**(s)**
。
当它们不匹配时,您不能使用方法引用。
或者您可以使用一些丑陋的解决方法:
Optional.ofNullable(null).orElseThrow(MyException::new);
class MyException extends RuntimeException {
public MyException() {
super("Invalid user id!");
}
}
但这是没有充分理由的大量开销。
推荐阅读
- dart - 如何从特定索引的列表中获取项目?
- sql - 选择查询以使用 BigQuery 对输出 json 中的记录进行分组
- gremlin - 无法在 Janusgraph 中使用 Cardinality.list 更新顶点属性
- python - 如何使用 Python 中的时间序列预测来预测未来日期?
- python - 抑制函数的输出
- c# - 在 C# 中使用 LINQ 从另外两个具有相同 ID 的数据表中创建一个新的 DataTable
- docker - 如何通过 Docker 网桥使用 Curl 从 Jenkins 将文件发布到 Go 服务器?
- c++ - 自定义创建 QFuture
- java - 如何使用 apache poi 复制/写入特定行
- spring - 将多个值从 jsp 发送到控制器