How to correctly use @ checkfornull, @ nonnull and @ nullable annotations of findbugs
I want to formally annotate my function signature to clarify their contract - especially if NULL params and return values are allowed or prohibited - in a way that findbugs's static code analysis tool (and possibly others) can use it
There are two packages (annotations. Jar and jsr305. Jar). Each package has four comments and the option not to add comments
Solution
After some attempts, these are my findings:
Method parameters:
>Parameter cannot be null: do not put any comments In this case, if NULL is passed to the method, an error flag will appear (I expected this behavior when I preset the @ nonnull annotation, but when I put it in, there was no error mark at all.) > Parameter can be null: place @ nullable comment (@ checkfornull has the same effect. @ nullable documentation reads: "findbugs will treat annotated items as uncommented." It is not true. If I call string Length() and the string string has been marked @ nullable, which will cause an error flag. If there is no comment, the error flag will not be displayed.)
Method return value:
>Method will never return null: place @ nonnull If you try to return null, it will result in an error flag; From within the method. > Method can return null: do you want to force it to be checked? If the return value does depend on method parameters that can only be assumed at the time of the call, the check may be an overhead, such as "if parameter 1 is negative, my method returns null" In this case, I will not give comments However, you may need to consider throwing an illegalargumentexception instead of returning null. > Method can return null, and the returned object should always be checked: place @ checkfornull However, in many cases, there are better ways, and you may need to consider returning collections Emptylist () instead of null list, or throw missingresourceexception, IOException or other appropriate exceptions
Which jar file to use:
>Both jar files will cause the same behavior of findbugs. The only difference is annotations The comments in the jar appear deprecated in eclipse So use jsr305 jar. > A jar file is required Creating an empty comment with the given package and class name does not work You can get it here