[英]Java transient keyword and null
I'm using Intellij IDEA, and the follow code generates a warning: " Expression testObj might evaluate to null but is returned by the method declared as @NotNull (at line 16)
" 我正在使用Intellij IDEA,并且以下代码生成一个警告:“ Expression testObj might evaluate to null but is returned by the method declared as @NotNull (at line 16)
”
package com.dlp;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class TestCase {
@Nullable
private transient Object testObj = null;
@Nonnull
public Object getTestObj() {
if(testObj == null) {
testObj = new Object();
}
return testObj; //Line 16
}
}
This only happens if I mark testObj as transient. 只有将testObj标记为瞬态时才会发生这种情况。 Removing the keyword clears the warning. 删除关键字会清除警告。 Is there some interaction between transient and nullability that I'm not getting, or is this just a bug in IDEA? 瞬态和可空性之间是否存在一些我没有得到的相互作用,或者这只是IDEA中的一个错误?
Nullability is very strict in the compiler. 编译器中的可空性非常严格。 Yes, you do check for null, but there is a problem in that your code might be used in a multi-threaded context. 是的,您确实检查了null,但是存在一个问题,即您的代码可能在多线程上下文中使用。 Consider this scenario: 考虑这种情况:
This block is executed: 执行此块:
if(testObj == null) {
testObj = new Object();
}
The current thread is pre-empted and another thread comes along and sets testObj
to null. 当前线程被抢占,另一个线程出现并将testObj
设置为null。 Then the original thread becomes live again and finishes execution and returns null
for testObj
. 然后原始线程再次变为活动并完成执行并为testObj
返回null
。
The proper way to write this code to avoid the null warning is like this: 编写此代码以避免空警告的正确方法如下:
public Object getTestObj() {
Object tmpObj = testObj
if(tmpObj == null) {
tmpObj = new Object();
testObj = tmpObj;
}
return tmpObj;
}
In this case, you are guaranteed that the return value is never null. 在这种情况下,您可以保证返回值永远不为null。
Granted, this is a pretty tight corner case and most programs will never need this level of safety, but that is how compilers should be checking for null. 当然,这是一个相当紧凑的案例,大多数程序永远不需要这种安全级别,但这就是编译器应该检查null的方式。
The fact that the null warning disappears when you add transient, seems like an IntelliJ bug. 添加瞬态时空值警告消失的事实看起来像是一个IntelliJ错误。 However, the suggested code above is the proper way to handle nullability for fields. 但是,上面建议的代码是处理字段可空性的正确方法。 If this is too onerous for you, I'd suggest avoiding adding null annotations on fields. 如果这对你来说太繁重,我建议避免在字段上添加空注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.