Search code examples
javaandroidandroid-studiointellij-ideaannotations

Is there a NonNullByDefault annotation for Android Studio


I am really missing @NonNullByDefault from eclipse in Android Studio. Is there a way to get this or something similar? I only saw one using javax's @TypeQualifierDefault, but this seems not to be available in the android project.


Solution

  • You can actually just add the eclipse annotation package to your project and use it.

    Simply add

    dependencies {
        implementation group: 'org.eclipse.jdt', name: 'org.eclipse.jdt.annotation', version: '2.2.600'
    }
    

    To your gradle and you can use the @NonNullByDefault annotations it provides.

    As usual you can either set it per class

    @NonNullByDefault
    public class MyClass {
        String test = "This is a non null string"
        @Nullable test2 = "This is a nullable string"
    
        public MyClass(String nonNullParam, @Nullable String nullableParam) {
            Object nonNullVar = nonNullParam;
            @Nullable Object nullableVar = nullableParam;
        }
    }
    

    Or you can set it for an entire package by creating a package-info.java file and in it

    @NonNullByDefault   
    package my.package;
    
    import org.eclipse.jdt.annotation.NonNullByDefault;
    

    You still need to activate the setting in https://stackoverflow.com/a/35942944/2075537 to have complete coverage in case you forget it on a package