Uploaded image for project: 'SonarJava'
  1. SonarJava
  2. SONARJAVA-2693

FP on S2259 when variable of foreach loop is annotated with @Nonnull

    Details

    • Type: False-Positive
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 5.3
    • Component/s: Rules, Symbolic Execution
    • Labels:
      None

      Description

      In the following code, the variable from the foreach loop is annotated with @Nonnull, which means that it explicitly says that all the items from the list are non-null. We should therefore start the exploration of the loop body with a non-null constraints on the variable, and therefore NOT learn from the method invocation that the item can be null.

      import java.util.List;
      import javax.annotation.Nonnull;
      
      abstract class A {
        void foo(List<A> items) {
          for (@Nonnull A item : items) {          // @Nonnull annotation should force non-null constraint
            Object o = qix(A.bar(item));           // A.bar(item) makes the engine learn 'item' can be null
            if ("foo".equals(o.toString())) {
              item.toString();                     // FP S2259
            }
          }
        }
      
        private static String bar(A item) {
          if (item != null) {
            return item.toString();
          }
          return null;
        }
      
        abstract Object qix(String s);
      }
      

        Attachments

          Activity

            People

            • Assignee:
              michael.gumowski Michael Gumowski
              Reporter:
              michael.gumowski Michael Gumowski
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Due:
                Created:
                Updated:
                Resolved: