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

后端 未结 3 1818
醉话见心
醉话见心 2020-11-28 20:44

I\'d like to use

java.util.Optional.orElseThrow()

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

相关标签:
3条回答
  • 2020-11-28 21:19
    optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
    
    0 讨论(0)
  • 2020-11-28 21:23

    Sure.

    .orElseThrow(() -> new MyException(someArgument))
    
    0 讨论(0)
  • 2020-11-28 21:36

    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.

    0 讨论(0)
提交回复
热议问题