使Java推断@NotNull为可选的返回类型 [英] Make Java infer @NotNull for Optional Return Types

查看:393
本文介绍了使Java推断@NotNull为可选的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中使用Optional不能保护NPE,因为值仍然可以是null:

Using Optionals 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为可选的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆