Java 8 method references: provide a Supplier capable of supplying a parameterized result

StackOverflow https://stackoverflow.com/questions/22917138

  •  29-06-2023
  •  | 
  •  

문제

I'd like to use

java.util.Optional.orElseThrow()

with an Exception type that asks for a constructor parameter. Something like this:

.orElseThrow(MyException::new(someArgument)) // obviously NOT working

Is there a way to create a Supplier that passes my argument value in?

도움이 되었습니까?

해결책

Sure.

.orElseThrow(() -> new MyException(someArgument))

다른 팁

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top