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



我正在寻找一种方法来处理null与使用可选的构造函数引用异常,在那里我想传递一个自定义消息异常。

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

我知道在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);

但我正在寻找一种方法来做它与可选使用构造函数引用。

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

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函数不可能。参考如何在Java8中通过::new初始化时将参数传递给类构造函数

最新更新