I am looking for a way to handle null with an Exception using Constructor reference with Optional, where I want to pass a custom message with Exception.
E.g. There is a service which offers getPassword(String userId) method to retrieve the password. It accepts one argument of type String, which is the userId. If the userId does not exist in the system, then it returns null, else returns password (String). Now I am calling this method and want to throw 'IllegalArgumentException' if null is returned.
I know there are many ways to do this in Java, but I am looking for a way to do it with Optional using Constructor reference.
//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);