java build返回空值,使Java推断@NotNull为可选的返回类型

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值