如何在 Java 8 中抛出异常时使用 Optional 中的构造函数引用传递异常消息

How to pass Exception message With Constructor Reference in Optional while throwing Exception in Java 8

我正在寻找一种方法来使用带有可选的构造函数引用来处理带有异常的空值,我想在其中传递带有异常的自定义消息。

例如有一项服务提供 getPassword(String userId) 方法来检索密码。它接受一个 String 类型的参数,即 userId。如果系统中不存在 userId,则它 returns null,否则 returns password (String)。现在我正在调用此方法并希望在返回 null 时抛出 'IllegalArgumentException'。

我知道在 Java 中有很多方法可以做到这一点,但我正在寻找一种方法来使用构造函数引用使用 Optional 来做到这一点。

//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);

but I am looking for a way to do it with Optional using Constructor reference.

你可以,当你的异常有一个无参数的构造函数时:

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

但是没有充分的理由这是很多开销。

lambda 函数不可能。 参考文献How to pass argument to class constructor when initialzed thru ::new in Java8