From 872afe794777f91e95adc40d3157d53c9f1b6144 Mon Sep 17 00:00:00 2001 From: Tomasz Tylenda Date: Fri, 22 Nov 2024 13:49:49 +0100 Subject: [PATCH] Modify S5411 explaining that @NonNull values are ignored. --- rules/S5411/java/rule.adoc | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/rules/S5411/java/rule.adoc b/rules/S5411/java/rule.adoc index 0d0c77d192e..890168d7082 100644 --- a/rules/S5411/java/rule.adoc +++ b/rules/S5411/java/rule.adoc @@ -5,7 +5,7 @@ When boxed type `java.lang.Boolean` is used as an expression to determine the co It is safer to avoid such conversion altogether and handle the `null` value explicitly. -Note, however, that no issues will be raised for Booleans that have already been null-checked. +Note, however, that no issues will be raised for Booleans that have already been null-checked or are marked `@NonNull/@NotNull`. === Noncompliant code example @@ -38,6 +38,35 @@ if(b != null){ } ---- +=== Exceptions + +The issue is not raised if the expression is annotated `@NonNull` / `@NotNull`. +This is useful if a boxed type is an instantiation of a generic type parameter +and cannot be avoided. + +[source,java] +---- +List list = new ArrayList<>(); +list.add(true); +list.add(false); +list.forEach((@NonNull Boolean value) -> { + // Compliant + if(value) { + System.out.println("yes"); + } +}); + +@NonNull Boolean someMethod() { /* ... */ } + +// Compliant +if(someMethod()) { /* ... */ } + +@NonNull Boolean boxedNonNull = Boolean.TRUE; + +// Compliant +if(boxedNonNull) { /* ... */ } +---- + == Resources * https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8[Java Language Specification ยง5.1.8 Unboxing Conversion]