首页 > 解决方案 > 在 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);

标签: javaoptional

解决方案


但我正在寻找一种使用构造函数参考的可选方法。

当您的 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!");
  }
}

但这是没有充分理由的大量开销。


推荐阅读