Using Optionals in Java does not protect from NPEs since values still can be null:
Optional myMethod() {
return null;
}
A way to protect from this at least at runtime is the use of @NotNull annotations. (Not possible at compile time in Java since it does not have non-null references, as opposed to more sophisticated languages like Swift and Kotlin).
Using @NotNull will immediately crash when null is detected, thus preventing null traversing through the program, and making it easier to pinpoint error sources. It's best combined with Unit Tests to make it resilient against breaking due to refactorings.
As far as I can tell, it always makes sense to use @NotNull for Optional return values and parameters.
Now here's the question:
Is it somehow possible to make Java infer @NotNull automatically for Optional return values and parameters? I.e. I don't have to write it for every use, but rather have that behaviour by setting some build setting or similar?
解决方案
Optional is not designed to keep only non null values . It may contain null values as well. So your proposal is against the design of the Optional.