29

I've made several attempts at getting package annotation @ParametersAreNonnullByDefault to work for me in a maven project but with no success. Could someone share a link to a minimal/sample maven project where this is setup (or post the pom.xml and package-info.java and demo class)?

I'm talking about having findbugs processor enforce it for me.

simpatico
  • 10,709
  • 20
  • 81
  • 126

2 Answers2

32

How to apply @ParametersAreNonnullByDefault

Create a file package-info.java in your package where you want to enforce the desired behavior.

In that file, do the following:

/**
 * You should do it like this!
 */
@ParametersAreNonnullByDefault
package com.stackoverflow;

import javax.annotation.ParametersAreNonnullByDefault;

How not to apply @ParametersAreNonnullByDefault

Don't do the following in a Java source file:

/**
 * But you shouldn't do it this way!
 */
@ParametersAreNonnullByDefault
package com.stackoverflow;

import javax.annotation.ParametersAreNonnullByDefault;

public class Answer { ...

Declaring annotations like this is ambiguous.

Notes

It would be OK to apply the annotation directly on Answer class.

package com.stackoverflow;

import javax.annotation.ParametersAreNonnullByDefault;

/**
 * You can do it like this also.
 */
@ParametersAreNonnullByDefault
public class Answer { ...

The exact same things apply to @ParametersAreNullableByDefault also.

Kohányi Róbert
  • 9,791
  • 4
  • 52
  • 81
  • 3
    Android users, you will need to add jsr-305 as a dependency. Google hosts a copy of it for Findbugs which can be used: https://mvnrepository.com/artifact/com.google.code.findbugs/jsr305 – Saket Jan 05 '18 at 01:55
  • Is there a way to apply it to an entire project? – Antony Stubbs May 04 '22 at 12:13
  • 1
    @AntonyStubbs Haven't tried, but maybe you can create a `package-info.java` at your package structure's top level, say for `com.example.project`, create a `package-info.java` in the `com` folder and test whether the effect of the annotation is recursively applied or not. Just a wild guess that it might work - if not, then I'd think this is the design principle behind the annotation and its effect: tell explicitly in every package where you want this to be the default. My suggestion tho': put it on every class - that's the most visible, easiest to understand. – Kohányi Róbert May 04 '22 at 14:24
4

For Android projects (for example when using libraries like Retrofit etc), this is the dependency to put in app/build.gradle (as mentioned by @Saket):

dependencies {
    implementation 'com.google.code.findbugs:jsr305:3.0.2'
    // ...
}
friederbluemle
  • 33,549
  • 14
  • 108
  • 109