This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: The use of @nullable annotations

I see some methods in Java declared as:

void foo(@Nullable Object obj)

{... }Copy the code

What does @nullable mean here? Does that mean the input can be null?

Without this annotation, the input can still be NULL, so I guess that’s not how it’s used?

Answer a

It clearly states that this method accepts null values, and that if you override the method, you should also accept null values.

It can also serve as a prompt for code profilers like FindBugs. For example, FindBugs would warn if such a method indirectly referred to its arguments without first checking for null values.

Answer two

This annotation is usually used to eliminate null-pointer exceptions. @nullable Indicates that the parameter may be NULL. A good example to use is Google Guice. In this lightweight dependency injection framework, you can indicate that the dependency may be empty. If you try to pass null values without annotations, the framework won’t do its job.

More importantly, @nullable can be used with the @notnull annotation. Here you can find some tips for using them properly. Code checking in IntelliJ also checks annotations and helps debug code.

Answer three

Of course, there’s definitely a different thought here, and my thought is that I can’t force “never pass null values” because I’m dealing with uncontrollable third party stuff, such as API calls, database records, previous programmer stuff, etc. So I’m paranoid about this approach. Because you’re using Java8 or later, there’s a cleaner way to do it than if blocks.

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

You can also throw exceptions by swapping.orelse to orElseThrow(() -> new Exception (” Don’t send a null”)).

If you don’t want to use @Nullable that doesn’t add any functionality, why not just name the argument mayB? So your thoughts are clear.

The article translated from Stack Overflow:stackoverflow.com/questions/1…