问题描述
在Java中使用Optional
不能保护NPE,因为值仍然可以是null
:
Using Optional
s in Java does not protect from NPEs since values still can be null
:
Optional<String> myMethod() {
return null;
}
至少在运行时避免这种情况的一种方法是使用@NotNull
批注. (在Java编译时是不可能的,因为它没有非null引用,与Swift和Kotlin等更复杂的语言相反).
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).
使用@NotNull
将在检测到null
时立即崩溃,从而防止null
遍历程序,并更容易查明错误源.最好将它与单元测试结合使用,以使其具有弹性,以防止因重构而损坏.
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.
据我所知,对于Optional
返回值和参数使用@NotNull
总是有意义的.
As far as I can tell, it always makes sense to use @NotNull
for Optional
return values and parameters.
现在是问题:是否可以通过某种方式使Java自动为Optional
返回值和参数推断@NotNull
? IE.我不必每次使用都编写它,而是通过设置一些构建设置或类似设置来具有这种行为?
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?
推荐答案
可选项并非仅保留非null值.它也可能包含空值.因此,您的建议与Optional的设计背道而驰.
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.
这篇关于使Java推断@NotNull为可选的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!