简体   繁体   中英

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.

I have not found a @NonNullByDefault functionality. BUT you can at least let the inspector handle all unannotated members & parameters as if they were annotated as @Nullable. Which will at least help to get 100% null-analyzation coverage. Basically a @NullByDefault.

检查器设置

I wrote a gradle script to handle project-wide @NonNullByDefault annotation for Android Studio.

It goes through all the subpackages to check whether package-info.java files are generated inside each of them.

The script is run before each assembleDebug task so that you can force @ParametersAreNonnullByDefault annotation on all java classes in your project.

NonNullByDefault for all java classes inside a project

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM