@Nullable annotation usage

后端 未结 4 1680
太阳男子
太阳男子 2020-11-27 09:17

I saw some method in java declared as:

void foo(@Nullable Object obj)
{ ... }

What\'s the meaning of @Nullable here? Does it m

相关标签:
4条回答
  • 2020-11-27 09:53

    Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

    0 讨论(0)
  • 2020-11-27 09:53

    Granted, there are definitely different thinking, in my world, I cannot enforce "Never pass a null" because I am dealing with uncontrollable third parties like API callers, database records, former programmers etc... so I am paranoid and defensive in approaches. Since you are on Java8 or later there is a bit cleaner approach than an if block.

    public String foo(@Nullable String mayBeNothing) {
       return Optional.ofNullable(mayBeNothing).orElse("Really Nothing");
    }
    

    You can also throw some exception in there by swapping .orElse to orElseThrow(() -> new Exception("Dont' send a null")).

    If you don't want to use @Nullable, which adds nothing functionally, why not just name the parameter with mayBe... so your intention is clear.

    0 讨论(0)
  • 2020-11-27 09:56

    It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

    It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

    0 讨论(0)
  • This annotation is commonly used to eliminate NullPointerExceptions. @Nullable says that this parameter might be null. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null. If you would try to pass null without an annotation the framework would refuse to do it's job.

    What is more @Nullable might be used with @NotNull annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.

    0 讨论(0)
提交回复
热议问题