在平时的开发过程中,我们一般会自定义函数对变量是否为 null 进行检查,当检查函数返回成功的时候,对象一定不是 null 。
但是,这个自定义的函数,对于 Android Studio/IntelliJ IDEA 来说,是无法感知到的,导致 Android Studio/IntelliJ IDEA 会发出警告,没有对变量是否为 null 进行检查。
出现上述问题的例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Random; public class Test { // validator method static boolean hasText(String s) { return !(s == null || s.trim().isEmpty()); } public static void main(String[] args) { // s could come from anywhere and is null iff the data does not exist String s = (new Random().nextBoolean()) ? "valid" : null; if (hasText(s)) { // Potential null pointer access: The variable s may be null at this location System.out.println(s.length()); // ... do actual stuff ... } } } |
那么,有没有办法告知 Android Studio/IntelliJ IDEA ,我们已经对 null 进行过检查了呢?
网上搜索许久,尝试过 @CheckForNull / @EnsuresNonNullIf 注解,都不能解决问题。
最终发现使用 jetbrains 的 @Contract 注解能解决此问题。
上述的例子增加以下注解,明确告知编译器,如果参数是 null 函数一定返回 false,就可以阻止编译器发出警告了。
如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Random; import org.jetbrains.annotations.Contract; public class Test { // validator method @Contract("null -> false") static boolean hasText(String s) { return !(s == null || s.trim().isEmpty()); } public static void main(String[] args) { // s could come from anywhere and is null iff the data does not exist String s = (new Random().nextBoolean()) ? "valid" : null; if (hasText(s)) { // Potential null pointer access: The variable s may be null at this location System.out.println(s.length()); // ... do actual stuff ... } } } |
参考链接
- Improve code inspection with annotations
- 利用注解改进代码检查
- @EnsuresNonNullIf annotation gives "conditional postcondition not satisfied"-warning
- How to avoid null warning when using @NotNull and checking for null in another method before method call?
- The Checker Framework
- javax.annotation: @Nullable vs @CheckForNull
- Validated variable null warning
- java isnull方法_java – 如何让IntelliJ IDEA理解我的null检查方法
- How to tell IDEA/Studio that the null check has been done?
- Better Control Flow Analysis with Contract Annotations and IntelliJ IDEA 13
- JetBrains注解@NotNull/@Nullable/@Contract