### Match Generated Subpackages with Restricted Regex Source: https://github.com/uber/nullaway/wiki/Configuration Uses a restricted regular expression syntax to match package names that start with a specific prefix, such as generated packages. The '.' character is treated literally. ```bash -XepOpt:NullAway:UnannotatedSubPackages=com.myorg.generated_[a-zA-Z0-9]* ``` -------------------------------- ### NullAway Basic Example: Buggy Code Source: https://github.com/uber/nullaway/blob/master/README.md A simple Java code example demonstrating a bug where a null value is passed to a method expecting a non-null object, leading to a potential NullPointerException. This snippet is intended to show the initial problem NullAway identifies. ```java static void log(Object x) { System.out.println(x.toString()); } static void foo() { log(null); } ``` -------------------------------- ### NullAway Contract Annotations Example Source: https://github.com/uber/nullaway/wiki/Supported-Annotations Demonstrates the usage of JetBrains' @Contract annotations within a Java class for specifying method contracts related to nullability. These annotations help NullAway understand method behavior. ```Java public class NullnessChecker { @Contract("_, null -> true") static boolean isNull(boolean flag, @Nullable Object o) { return o == null; } @Contract("null -> false") static boolean isNonNull(@Nullable Object o) { return o != null; } @Contract("null -> fail") static void assertNonNull(@Nullable Object o) { if (o == null) throw new Error(); } @Contract("!null -> !null") static @Nullable Object id(@Nullable Object o) { return o; } } ``` -------------------------------- ### Configure NullAway Excluded Field Annotations Source: https://github.com/uber/nullaway/wiki/Configuration Lists annotations that, when present on fields, will exclude those fields from NullAway's checks for proper initialization. An example includes javax.inject.Inject. This option supports restricted regexp syntax. ```bash -XepOpt:NullAway:ExcludedFieldAnnotations=... ``` -------------------------------- ### NullAway Basic Example: Fixing Null Dereference Source: https://github.com/uber/nullaway/blob/master/README.md This Java code demonstrates the final fix for NullAway warnings. By adding a null check before dereferencing the object, the potential null pointer exception is avoided, and all NullAway warnings are resolved. ```java static void log(@Nullable Object x) { if (x != null) { System.out.println(x.toString()); } } ``` -------------------------------- ### Java: Initialize Map Value with put() for Non-Null Source: https://github.com/uber/nullaway/wiki/Maps Shows how initializing a map value using put() can help NullAway infer non-nullability for subsequent get() calls. This assumes the newValue being put is also @NonNull. ```Java if (!m.containsKey(key)) { m.put(key,newValue); } // here m.get(key) is @NonNull, assuming newValue is @NonNull ``` -------------------------------- ### Java: Check Map.get() Nullability Directly Source: https://github.com/uber/nullaway/wiki/Maps Demonstrates how to check the nullness of a Map.get() call directly in Java. If the result of m.get(key) is not null, NullAway infers that it is @NonNull. ```Java if (m.get(key) != null) { // here m.get(key) is @NonNull } ``` -------------------------------- ### Java: Ensure Non-Null Map.get() using containsKey() Source: https://github.com/uber/nullaway/wiki/Maps Illustrates using containsKey() to ensure that a subsequent Map.get() call returns a non-null value. If the key exists, NullAway infers the get() result is @NonNull. ```Java if (m.containsKey(key)) { // here m.get(key) is @NonNull } ``` -------------------------------- ### NullAway Type Inference Example: Complex Expressions Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works Illustrates NullAway's inference for more complex expressions, such as chained method calls on object fields. It shows how NullAway can determine nullability for nested access paths. ```Java class ListNode { int data; @Nullable ListNode next; @Nullable ListNode getNext() { return next; } void doStuff() { if (this.next != null && this.next.getNext() != null) { // NullAway infers this.next.getNext() to be @NonNull here this.next.getNext().toString(); } } } ``` -------------------------------- ### Dereferencing a Nullable Expression in Java Source: https://github.com/uber/nullaway/wiki/Error-Messages Demonstrates how NullAway flags the dereferencing of a nullable expression, which can lead to null pointer exceptions. It shows an example of unsafe dereferencing and provides a corrected version with a null check. ```Java Object x = null; x.toString(); // dereferencing x, which is null ``` ```Java Object x = null; if (x != null) { x.toString(); // this is safe now } ``` -------------------------------- ### NullAway Basic Example: Fixing NPE with @Nullable Source: https://github.com/uber/nullaway/blob/master/README.md This Java code snippet shows how to fix the NullAway warning by annotating the method parameter with `@Nullable`. This indicates that the parameter can accept null values, which then prompts NullAway to check for potential null dereferences. ```java static void log(@Nullable Object x) { System.out.println(x.toString()); } ``` -------------------------------- ### NullAway Type Inference Example: Basic Null Check Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works Demonstrates NullAway's ability to infer nullability within a method. It shows how a variable known to be non-null inside an if block is still considered nullable outside, leading to error reporting. ```Java void foo(@Nullable Object x) { if (x != null) { // inference learns x is @NonNull here x.toString(); } // x is still @Nullable here, hence error is reported x.hashCode(); } ``` -------------------------------- ### Java: Custom NullAway Downcast Method Source: https://github.com/uber/nullaway/wiki/Suppressing-Warnings Provides an example of a custom `castToNonNull` method in Java. This method takes a nullable type and returns it as a non-nullable type, handling potential nulls by logging or throwing an exception. It's useful when NullAway cannot infer non-nullability. ```Java import org.checkerframework.checker.nullness.qual.Nullable; public class NullAwayUtils { public static T castToNonNull(@Nullable T x) { if (x == null) { // YOUR ERROR LOGGING AND REPORTING LOGIC GOES HERE // For example: throw new AssertionError("Unexpected null value"); // Or: System.err.println("Unexpected null value"); } return x; } // Example usage: // void foo(Map map) { // if (map.containsKey("hello")) { // String value = castToNonNull(map.get("hello")); // // ... use value ... // } // } } ``` -------------------------------- ### Java: Workaround for Complex Keys in Map Checks Source: https://github.com/uber/nullaway/wiki/Maps Provides a workaround for NullAway's inability to track nullability with complex expressions used as map keys. Storing the complex expression in a local variable allows NullAway to correctly infer non-nullability. ```Java Object key = x.foo(y).baz(a,b); if (m.containsKey(key)) { // checker knows m.get(key) is @NonNull here } ``` -------------------------------- ### Read @NonNull Field Before Initialization in Java Source: https://github.com/uber/nullaway/wiki/Error-Messages This error occurs when a field annotated with @NonNull is accessed before it has been assigned a value. The provided example shows a common scenario where `this.foo.toString()` is called within the constructor before `this.foo` is initialized, leading to a NullPointerException. The solution is to ensure the field is initialized before any read operations. ```Java class C { Object foo; C() { this.foo.toString(); // foo not initialized yet! this.foo = new Object(); } } ``` -------------------------------- ### Unbound Instance Method Reference Error in Java Source: https://github.com/uber/nullaway/wiki/Error-Messages This error occurs when an unbound instance method reference is used as the first parameter of a functional interface method, and that parameter is annotated as @Nullable. This can lead to a NullPointerException if the method is called with a null argument. The example demonstrates how `Test::instMethod` is equivalent to `x -> x.instMethod()`, causing an issue when passed to `doApply` with a null value. ```Java interface NullableArgFunc { void apply(@Nullable T o); } class Test { static void doApply(NullableArgFunc f, @Nullable T p) { f.apply(p); } void instMethod() {} static void test() { doApply(Test::instMethod, null); // NullPointerException } } ``` -------------------------------- ### Prepare and Execute NullAway Release Source: https://github.com/uber/nullaway/blob/master/RELEASING.md Commands for preparing a release, including updating version numbers, committing changes, tagging the release, publishing artifacts, and pushing to remote repositories. ```git git commit -am "Prepare for release X.Y.Z." git tag -a vX.Y.Z -m "Version X.Y.Z" git push && git push --tags ``` -------------------------------- ### Build Project with NullAway Sample Source: https://github.com/uber/nullaway/blob/master/README.md This bash command demonstrates how to build a project with NullAway using Gradle. It involves copying a buggy sample file and then executing the Gradle build command to observe NullAway's error reporting. ```bash cp sample/src/main/java/com/uber/mylib/MyClass.java.buggy sample/src/main/java/com/uber/mylib/MyClass.java ./gradlew build ``` -------------------------------- ### Build NullAway jar-infer with Gradle Source: https://github.com/uber/nullaway/blob/master/jar-infer/jar-infer-cli/README.md This snippet shows the Gradle commands to build the NullAway jar-infer tool. It automatically downloads necessary dependencies like WALA. ```Shell gradle wrapper ./gradlew build ``` -------------------------------- ### Run NullAway jar-infer CLI Tool Source: https://github.com/uber/nullaway/blob/master/jar-infer/jar-infer-cli/README.md This snippet demonstrates how to execute the NullAway jar-infer command-line tool. It takes input and output file paths, with optional parameters for package name, verbosity, and debug information. ```Java java -jar -i -o [-p ] [-vdh] ``` -------------------------------- ### Gradle Build and Publish Command Source: https://github.com/uber/nullaway/blob/master/RELEASING.md Command to clean the project and publish the build artifacts using Gradle. ```bash ./gradlew clean publish ``` -------------------------------- ### Configure NullAway Known Initializers Source: https://github.com/uber/nullaway/wiki/Configuration Lists fully qualified method names (without arguments) from third-party libraries that NullAway should recognize as initializers, similar to methods annotated with @Initializer. ```bash -XepOpt:NullAway:KnownInitializers=... ``` -------------------------------- ### Configure Bazel BUILD file for NullAway Integration Source: https://github.com/uber/nullaway/wiki/Configuration This Bazel BUILD file configuration demonstrates how to integrate NullAway as a Java plugin. It specifies the library to be compiled, dependencies including jsr305, and compiler options to enable NullAway with specific annotated packages. ```python java_library( name='x', srcs=['X.java'], deps=['@jsr305//jar'], plugins=['nullaway'], javacopts=[ '-Xep:NullAway:ERROR', '-XepOpt:NullAway:AnnotatedPackages=com.example', ], ) java_plugin( name='nullaway', deps=[ '@nullaway//jar' ], ) ``` -------------------------------- ### Configure Maven Compiler Plugin for NullAway Source: https://github.com/uber/nullaway/wiki/Configuration This configuration sets up the Maven compiler plugin to include Error Prone and NullAway. It specifies Java versions, encoding, and compiler arguments, including NullAway's annotated packages option. It also lists the necessary dependencies for Error Prone and NullAway. ```xml org.apache.maven.plugins maven-compiler-plugin 3.11.0 11 11 UTF-8 -XDcompilePolicy=simple -Xplugin:ErrorProne -XepOpt:NullAway:AnnotatedPackages=com.uber com.google.errorprone error_prone_core 2.23.0 com.uber.nullaway nullaway 0.10.15 ``` -------------------------------- ### Publish Unsigned Local Build with Gradle Source: https://github.com/uber/nullaway/blob/master/RELEASING.md This command allows publishing a non-SNAPSHOT build locally without signing by overriding the RELEASE_SIGNING_ENABLED property in Gradle. ```bash ORG_GRADLE_PROJECT_RELEASE_SIGNING_ENABLED=false ./gradlew publishToMavenLocal ``` -------------------------------- ### Fix @EnsuresNonNullIf: Return Boolean Source: https://github.com/uber/nullaway/wiki/Error-Messages This code snippet addresses an error where a method annotated with @EnsuresNonNullIf fails to return a boolean value. The example illustrates the correct usage, emphasizing that such methods must have a boolean return type to indicate the conditional non-nullability of fields. ```Java class Foo { @Nullable private Object item; @EnsuresNonNullIf("item") public boolean hasItem() { // CORRECT: this method returns boolean return item != null; } } ``` -------------------------------- ### Configure NullAway Annotated Packages Source: https://github.com/uber/nullaway/wiki/Configuration Specifies the list of Java packages that NullAway should consider as properly annotated with nullability conventions. This option supports restricted regular expression syntax for package patterns. ```bash -XepOpt:NullAway:AnnotatedPackages=... ``` -------------------------------- ### Specify Custom Optional Classes for Emptiness Check in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Provide a list of custom `Optional` implementations (e.g., Guava's `Optional`) for NullAway to analyze for emptiness. ```Java -XepOpt:NullAway:CheckOptionalEmptinessCustomClasses=... ``` -------------------------------- ### Handle Test Assertion Libraries in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Enable this option to allow NullAway to understand assertions from test libraries (e.g., `assertThat(...).isNotNull()`) and use them to infer nullability information. ```Java -XepOpt:NullAway:HandleTestAssertionLibraries=true ``` -------------------------------- ### Fix @EnsuresNonNullIf: Ensure Field Non-Nullability Source: https://github.com/uber/nullaway/wiki/Error-Messages This code snippet demonstrates a common error where a method annotated with @EnsuresNonNullIf does not guarantee the non-nullability of the specified field. The example shows a corrected implementation where the method's return value accurately reflects the nullability of the 'item' field. ```Java class Foo { @Nullable private Object item; @EnsuresNonNullIf("item") public boolean hasItem() { // Correct implementation: returns true only if item is non-null return item != null; } public void operation() { if(!hasItem()) { return; } // from here on, item is assumed to be non-null } } ``` -------------------------------- ### Configure Bazel WORKSPACE for NullAway Dependencies Source: https://github.com/uber/nullaway/wiki/Configuration This snippet shows how to define Maven dependencies for jsr305 and NullAway within a Bazel WORKSPACE file. These are required for NullAway to function correctly in a Bazel build environment. ```python maven_jar( name='jsr305', artifact='com.google.code.findbugs:jsr305:3.0.2', ) maven_jar( name="nullaway", artifact="com.uber.nullaway:nullaway:0.3.4" ) ``` -------------------------------- ### Specify Custom Contract Annotations for NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Allows NullAway to recognize additional annotations as contract providers, beyond the default `org.jetbrains.annotations.Contract`. This extends NullAway's ability to analyze custom contract annotations using the same syntax. ```bash -XepOpt:NullAway:CustomContractAnnotations=com.example.MyContractAnnotation ``` -------------------------------- ### Configure Custom Initializer Annotations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Define custom annotations that mark methods as initializers in NullAway. This allows NullAway to correctly identify methods responsible for initializing objects, similar to JUnit's @Before or @BeforeClass. Fully-qualified class names are necessary. ```Java -XepOpt:NullAway:CustomInitializerAnnotations=... ``` -------------------------------- ### Configure NullAway Unannotated Sub-packages Source: https://github.com/uber/nullaway/wiki/Configuration Defines a list of sub-packages within the 'AnnotatedPackages' that should be excluded from NullAway's nullability analysis. This option also supports restricted regular expression syntax. ```bash -XepOpt:NullAway:UnannotatedSubPackages=... ``` -------------------------------- ### Unboxing @Nullable Value in Java Source: https://github.com/uber/nullaway/wiki/Error-Messages This error is reported when a value annotated as @Nullable is implicitly unboxed by an operation, potentially causing a NullPointerException. The example illustrates this with `int i2 = i1 + 3;` where `i1` is null. Similar to dereferencing a nullable expression, the fix involves ensuring the value is not null before unboxing or explicitly handling the null case. ```Java Integer i1 = null; int i2 = i1 + 3; // NullPointerException ``` -------------------------------- ### Add Extra Futures Classes for NullAway Analysis Source: https://github.com/uber/nullaway/wiki/Configuration Provides NullAway with special handling for additional classes that behave like Guava's `Futures` and `FluentFuture`. This is a temporary measure to improve reasoning about callbacks in these classes. ```bash -XepOpt:NullAway:ExtraFuturesClasses=com.example.MyFutureClass ``` -------------------------------- ### Integrate NullAway with Gradle Source: https://github.com/uber/nullaway/blob/master/README.md This snippet shows how to configure NullAway as a Gradle plugin for Java projects. It requires Error Prone version 2.14.0 or higher. ```gradle plugins { id "com.uber.nullaway" } dependencies { errorprone "com.google.errorprone:error_prone_core:2.14.0" } ``` -------------------------------- ### Configure NullAway Unannotated Classes Source: https://github.com/uber/nullaway/wiki/Configuration Specifies a list of individual classes within annotated packages that NullAway should treat as unannotated, allowing for granular control over analysis. ```bash -XepOpt:NullAway:UnannotatedClasses=... ``` -------------------------------- ### Match Unannotated Subpackages with Restricted Regex Source: https://github.com/uber/nullaway/wiki/Configuration Uses a restricted regular expression syntax to identify subpackages that should be considered unannotated by NullAway. The '.' character is treated literally. ```bash -XepOpt:NullAway:UnannotatedSubPackages=[a-zA-Z0-9.]*.unannotated ``` -------------------------------- ### Enable NullAway Contract Checking Source: https://github.com/uber/nullaway/wiki/Configuration Enables NullAway to validate the correctness of JetBrains `@Contract` annotations. This option ensures that the specified annotations adhere to NullAway's supported subset of contract syntax. ```bash -XepOpt:NullAway:CheckContracts=true ``` -------------------------------- ### Configure NullAway Excluded Class Annotations Source: https://github.com/uber/nullaway/wiki/Configuration Provides a list of annotations that, when present on a class, will cause that class to be excluded from NullAway's nullability analysis. Callers into these classes are still assumed to have correctly annotated APIs. ```bash -XepOpt:NullAway:ExcludedClassAnnotations=... ``` -------------------------------- ### Acknowledge Restrictive Annotations from Third-Party Jars in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Enable this option to allow NullAway to respect nullability annotations from third-party libraries, even if they are more restrictive than NullAway's defaults. This enhances safety when dealing with external code. ```Java -XepOpt:NullAway:AcknowledgeRestrictiveAnnotations=true ``` -------------------------------- ### Re-enable Legacy Annotation Locations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Restores NullAway's previous interpretation logic for type-use annotations, aligning with JSpecify specifications. This option is intended to ease migration from older NullAway versions. ```bash -XepOpt:NullAway:LegacyAnnotationLocations=true ``` -------------------------------- ### Configure External Initialization Annotations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Specify annotations for classes that are initialized externally, meaning NullAway doesn't need to verify the initialization of non-null fields in their zero-argument constructors. This also applies when these annotations directly annotate a zero-argument constructor. ```Java -XepOpt:NullAway:ExternalInitAnnotations=... ``` -------------------------------- ### Configure Custom Nullable Annotations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Specify custom annotations to be recognized as nullable by NullAway. This is useful for projects using non-standard nullability annotations. The option requires fully-qualified class names. ```Java -XepOpt:NullAway:CustomNullableAnnotations=... ``` -------------------------------- ### Enable Type Annotations from Bytecodes (JDK 21) Source: https://github.com/uber/nullaway/wiki/JSpecify-Support When using JDK 21, this flag is recommended to enable proper support for reading type use annotations from bytecodes. This is crucial for NullAway's JSpecify integration. ```javac -XDaddTypeAnnotationsToSymbol=true ``` -------------------------------- ### Update JarInfer Android SDK Models Source: https://github.com/uber/nullaway/blob/master/RELEASING.md Steps to update JarInfer Android SDK models, involving modifying Gradle properties, obtaining AOSP framework intermediates, configuring JarInfer, and running the model generation script. ```python python jar-infer/scripts/android-jar.py ``` -------------------------------- ### Legacy Annotation Location Compatibility Source: https://github.com/uber/nullaway/wiki/JSpecify-Support This flag reverts NullAway to its old logic for interpreting annotations, which can help ease the transition to JSpecify's stricter requirements on annotation placement. It is recommended for existing users but will be removed in a future release. ```javac -XepOpt:NullAway:LegacyAnnotationLocations ``` -------------------------------- ### Enable Optional Emptiness Check in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration When `true`, NullAway checks for `.get()` calls on potentially empty `Optional` values, similar to dereferencing nullable values. This helps prevent runtime errors. ```Java -XepOpt:NullAway:CheckOptionalEmptiness=true ``` -------------------------------- ### Configure NullAway Excluded Classes Source: https://github.com/uber/nullaway/wiki/Configuration Specifies a list of classes to be completely excluded from NullAway's nullability analysis. Similar to excluded class annotations, the APIs of these classes are assumed to be correctly annotated when analyzing callers. ```bash -XepOpt:NullAway:ExcludedClasses=... ``` -------------------------------- ### Treat Generated Code as Unannotated in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Configure NullAway to treat classes annotated with @Generated as if their APIs are unannotated and to skip analysis within these classes. This is useful for managing generated code, though annotating the generated code directly is recommended if possible. ```Java -XepOpt:NullAway:TreatGeneratedAsUnannotated=true ``` -------------------------------- ### Configure Custom NonNull Annotations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Specify custom annotations to be recognized as non-null by NullAway. This is relevant for cases where NullAway needs to consider specific non-null annotations from third-party libraries. Fully-qualified class names are required. ```Java -XepOpt:NullAway:CustomNonnullAnnotations=... ``` -------------------------------- ### Configure NullAway to Use Only @NullMarked (Version 0.12.3+) Source: https://github.com/uber/nullaway/wiki/Configuration Enables NullAway to treat code annotated with JSpecify's @NullMarked as properly annotated, omitting the need for the AnnotatedPackages flag. This option cannot be used with AnnotatedPackages. ```bash -XepOpt:NullAway:OnlyNullMarked=true ``` -------------------------------- ### Configure Lombok for NullAway Source: https://github.com/uber/nullaway/blob/master/README.md This configuration option for Lombok ensures that NullAway can detect generated code within the in-memory Java AST by adding the `@lombok.Generated` annotation to generated methods and classes. NullAway will then ignore this generated code. ```properties lombok.addLombokGeneratedAnnotation = true ``` -------------------------------- ### Configure NullAway to Acknowledge Library Models Source: https://github.com/uber/nullaway/wiki/Configuration This configuration option for NullAway allows library models to override the annotations on methods within an annotated package. This is particularly useful when you want to treat certain packages as annotated but still leverage the default library models for their APIs. ```Java -XepOpt:NullAway:AcknowledgeLibraryModelsOfAnnotatedCode=... ``` -------------------------------- ### Enable Assertion Checks in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Configure NullAway to assume that assertion statements are always enabled at runtime. By default, NullAway ignores assertions because they may not be checked. Setting this option to true enables NullAway to rely on nullness checks within assertions. ```Java -XepOpt:NullAway:AssertsEnabled=true ``` -------------------------------- ### Suppressing Library Models in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration This command-line option allows you to ignore specific library models for a given compilation. It takes a comma-separated list of fully-qualified method names to be skipped by NullAway. ```bash -XepOpt:NullAway:IgnoreLibraryModelsFor=com.example.Foo.bar,com.example.Foo.baz ``` -------------------------------- ### Enable Exhaustive Override Checks in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Set this to `true` to force NullAway to check all methods for overrides, even if they lack the `@Override` annotation. This is useful for codebases with inconsistent `@Override` usage. ```Java -XepOpt:NullAway:ExhaustiveOverride=true ``` -------------------------------- ### Enable JSpecify Mode in NullAway Source: https://github.com/uber/nullaway/wiki/JSpecify-Support This flag enables NullAway to support full JSpecify semantics, including annotations on generic types. This mode is under development and may introduce false positives or crashes. ```javac -XepOpt:NullAway:JSpecifyMode=true ``` -------------------------------- ### NullAway @NonNull Field Initialization Check (Java) Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works Uses dataflow analysis to ensure @NonNull fields are initialized on all paths within constructors or initializer methods. ```Java // Dataflow analysis to track field initialization status // Checks if field is guaranteed to be @NonNull at constructor exit ``` -------------------------------- ### Configure Custom Generated Code Annotations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Specify a list of fully-qualified annotation names to mark code as generated. This helps NullAway ignore generated code during analysis. It works well with the `TreatGeneratedAsUnannotated` option. ```Java -XepOpt:NullAway:CustomGeneratedCodeAnnotations=... ``` -------------------------------- ### Extend NullAway with Custom Handlers Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works This snippet illustrates the general approach to extending NullAway. It involves subclassing `BaseNoOpHandler` and overriding specific methods to customize NullAway's behavior, such as handling library models or contract annotations. ```Java import com.uber.nullaway.handlers.BaseNoOpHandler; import com.uber.nullaway.handlers.Handler; // Example of a custom handler extending BaseNoOpHandler public class CustomHandler extends BaseNoOpHandler { @Override public void onDataflowVisitMethodInvocation( Handler.DataflowVisitMethodInvocationArguments args) { // Custom logic for method invocation analysis super.onDataflowVisitMethodInvocation(args); } // Override other relevant methods from the Handler interface as needed } ``` -------------------------------- ### Configure NullAway in Non-Android Java Gradle Projects Source: https://github.com/uber/nullaway/blob/master/README.md This snippet shows how to add NullAway to a non-Android Java project's build.gradle file. It includes dependencies for the Error Prone plugin, NullAway itself, JSpecify for annotations, and Error Prone core. It also configures Error Prone to treat NullAway issues as errors and specifies packages to be checked, with an option to disable NullAway for test code. ```gradle plugins { // we assume you are already using the Java plugin id "net.ltgt.errorprone" version "" } dependencies { errorprone "com.uber.nullaway:nullaway:" // Some source of nullability annotations; JSpecify recommended, // but others supported as well. api "org.jspecify:jspecify:1.0.0" errorprone "com.google.errorprone:error_prone_core:" } import net.ltgt.gradle.errorprone.CheckSeverity tasks.withType(JavaCompile) { options.errorprone { check("NullAway", CheckSeverity.ERROR) option("NullAway:AnnotatedPackages", "com.uber") } // Include to disable NullAway on test code if (name.toLowerCase().contains("test")) { options.errorprone { disable("NullAway") } } } ``` -------------------------------- ### NullAway Lambda and Method Reference Checks (Java) Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works Handles nullability checks for Java 8 lambdas and method references, treating them as method overrides and managing corner cases like unbound instance methods. ```Java // Special handling for lambdas and method references // Checking against functional interface method contracts // Handling cases like unbound instance methods ``` -------------------------------- ### Configure NullAway Suppression Name Aliases Source: https://github.com/uber/nullaway/wiki/Configuration Defines aliases for suppressing NullAway warnings using `@SuppressWarnings`. This is useful for consolidating suppression strategies, especially when other warnings are already being suppressed. ```bash -XepOpt:NullAway:SuppressionNameAliases=NullAway,OtherWarning ``` -------------------------------- ### NullAway: Filter Stream by Nullness Source: https://github.com/uber/nullaway/wiki/Stream-Handling Demonstrates how NullAway understands nullness facts after filtering a stream. It correctly identifies that elements remaining after a null check in a filter are non-null, preventing false positive dereference errors in subsequent operations. ```Java class Foo { @Nullable Bar f; } ... Stream stream = ...; stream .filter(x -> x.f != null) .forEach(x -> System.out.println(x.f.g)); // no warning reported ``` -------------------------------- ### LibraryModelsHandler: Nullability for Unannotated Methods Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works The `LibraryModelsHandler` customizes NullAway's default assumption that unannotated methods return `@NonNull`. It uses service loaders to find custom models and can override return nullability based on these models, allowing for `@Nullable` return values when specified. ```Java import com.uber.nullaway.handlers.Handler; // ... inside LibraryModelsHandler implementation ... // Override onDataflowVisitMethodInvocation to change return nullability @Override public void onDataflowVisitMethodInvocation( Handler.DataflowVisitMethodInvocationArguments args) { // Logic to check for custom library models and adjust nullability assumption // For example, if a model indicates @Nullable return, NullAway will propagate that. super.onDataflowVisitMethodInvocation(args); } // Other overrides for argument nullability and method overriding checks ``` -------------------------------- ### NullAway Read-Before-Init Check (Java) Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works Employs dataflow analysis to infer field nullability before a read operation, detecting potential read-before-initialization errors. ```Java // Dataflow analysis to infer nullability at program points // Checks for reads of fields before they are guaranteed to be initialized ``` -------------------------------- ### ApacheThriftIsSetHandler: Nullability for Thrift Generated Code Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works The `ApacheThriftIsSetHandler` correctly interprets `isSetXXXX()` methods generated by the Apache Thrift library. It treats these calls as checks for the nullability of the corresponding property `XXXX`. ```Java import com.uber.nullaway.handlers.Handler; // ... inside ApacheThriftIsSetHandler implementation ... // Example usage with Thrift generated code: // if (thriftObject.isSetMyProperty()) { // // NullAway understands this checks if MyProperty is non-null. // } ``` -------------------------------- ### Acknowledge Android 'Recent' Nullability Annotations in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration When enabled along with `AcknowledgeRestrictiveAnnotations`, this flag treats Android's `@RecentlyNullable` and `@RecentlyNonNull` annotations as equivalent to `@Nullable` and `@NonNull`, respectively. ```Java -XepOpt:Nullaway:AcknowledgeAndroidRecent=true ``` -------------------------------- ### NullAway: Synchronous Callback Handling (Collection.removeIf) Source: https://github.com/uber/nullaway/wiki/Stream-Handling Illustrates NullAway's handling of synchronous callbacks, specifically with Collection.removeIf. It propagates nullability facts from the containing method to the lambda, assuming the callback is executed immediately and safely. ```Java Foo x = ...; Collection c = ...; if (x.f != null) { c.removeIf((y) -> x.f.toString().equals(y)); } ``` -------------------------------- ### Java: Empty @RequiresNonNull/@EnsuresNonNull Annotation Source: https://github.com/uber/nullaway/wiki/Error-Messages Reports an error when @RequiresNonNull or @EnsuresNonNull annotations are used without specifying any parameters. These empty annotations are redundant as they represent the default precondition for all methods. ```Java class C { Object foo; @EnsuresNonNull() //Here the following error will be reported since no class field is given in parameters void ensures(){ } @RequiresNonNull() //Here the following error will be reported since no class field is given in parameters void requires(){ } } ``` -------------------------------- ### Java: Suppress NullAway Initialization Warnings Source: https://github.com/uber/nullaway/wiki/Suppressing-Warnings Shows how to suppress only NullAway warnings related to missing initialization for fields or constructors. This annotation targets specific initialization issues, providing finer-grained control than general suppression. ```Java public class Example { @SuppressWarnings("NullAway.Init") private String myField; @SuppressWarnings("NullAway.Init") public Example() { // Initialization warnings suppressed for this constructor } @SuppressWarnings("NullAway.Init") public static class MyClass { // Initialization warnings suppressed for this class } } ``` -------------------------------- ### RxNullabilityPropagator: Nullability in Rx Streams Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works The `RxNullabilityPropagator` handler propagates nullability information across call boundaries within Rx streams. This allows NullAway to correctly infer nullability for operations like `filter` and `map` on observables. ```Java import com.uber.nullaway.handlers.Handler; // ... inside RxNullabilityPropagator implementation ... // Example usage within an Rx stream: // observable.filter(o -> o != null).map(o -> o.toString()); // The handler ensures nullability is correctly tracked through these operations. ``` -------------------------------- ### Specify `castToNonNull` Method in NullAway Source: https://github.com/uber/nullaway/wiki/Configuration Define the method used for casting nullable expressions to non-null. NullAway will warn if a downcast is performed on an expression that is already non-null. ```Java -XepOpt:NullAway:CastToNonNullMethod=[...] ``` -------------------------------- ### ContractHandler: @Contract Annotation Support Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works The `ContractHandler` enables NullAway to understand a subset of the `@Contract` annotation. This allows specifying conditions for method return values, such as ensuring a non-null return if the input is non-null (`@Contract("!null -> !null")`). ```Java import com.uber.nullaway.handlers.Handler; // ... inside ContractHandler implementation ... // Example @Contract annotation: // @Contract("!null -> !null") // public String processNonNullString(String input) { // return input; // } // The handler interprets this to ensure the return value is treated as non-null. ``` -------------------------------- ### Implement Optional Emptiness Handling in NullAway Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works This handler extends NullAway to prevent `.get()` calls on Optional values without checking for emptiness. It treats optional values similarly to @Nullable values, requiring no core tool modifications. ```Java package com.uber.nullaway.handlers; import com.uber.nullaway.Handler; import com.uber.nullaway.NullAway; import com.uber.nullaway.dataflow.NullAnalysis; import com.uber.nullaway.generics.GenericsChecks; import com.uber.nullaway.util.SourcePosition; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import java.util.Optional; /** * Implements our support for preventing `.get(...)` calls on {@code Optional} values without checking that the {@code Optional} is non-empty. */ public class OptionalEmptinessHandler extends Handler { @Override public void onMatchMethodInvocation(MethodInvocationTree tree, NullAway analysis) { // Implementation details for handling Optional emptiness // This is a placeholder and would contain the actual logic. super.onMatchMethodInvocation(tree, analysis); } @Override public void onMatchNewClass(NewClassTree tree, NullAway analysis) { // Implementation details for handling Optional emptiness in new class instantiations // This is a placeholder and would contain the actual logic. super.onMatchNewClass(tree, analysis); } // Other overridden methods from Handler interface as needed... } ``` -------------------------------- ### Enable JSpecify Mode in NullAway Source: https://github.com/uber/nullaway/wiki/How-NullAway-Works This flag enables NullAway's support for the JSpecify specification, including nullability annotations on generic type arguments. Support for @NullMarked and @NullUnmarked annotations is on by default. ```Java // To enable JSpecify support, pass this flag during NullAway analysis: // -XepOpt:NullAway:JSpecifyMode // Relevant code for JSpecify support is in the com.uber.nullaway.generics package. // Specifically, the GenericsChecks class handles much of the JSpecify logic. // Example of how a flag might be processed (conceptual): // public class NullAwayOptions { // private boolean jspecifyMode = false; // // public void parseFlags(List flags) { // for (String flag : flags) { // if (flag.equals("-XepOpt:NullAway:JSpecifyMode")) { // this.jspecifyMode = true; // } // } // } // // public boolean isJSpecifyModeEnabled() { // return jspecifyMode; // } // } ```