SonarQube 6.7.1 LTS中Java规则S2637的疑似误报问题
testGregorianCalendar2()? Great question—this inconsistency boils down to how SonarQube 6.7.1's static analysis handles method contracts, nullability annotations, and flow tracking, which had notable limitations compared to newer versions. Let's break this down method by method:
First, a quick recap: S2637 is the SonarQube rule that flags methods annotated with @Nonnull that have a possible path to return null.
Breakdown of each method
testGregorianCalendar1(): SonarQube 6.7.1 recognizes thatGregorianCalendar.getInstance()is a standard JDK method with a well-documented contract of never returningnull. Since you're directly returning this non-null value and annotating the method with@Nonnull, the rule correctly doesn't flag it.testGregorianCalendar3(): ThesetTimeZone3()method does nothing but return its input directly—no null checks, no branches that returnnull. Even thoughsetTimeZone3()doesn't have a@Nonnullannotation, SonarQube's flow analysis tracks that the input coming fromGregorianCalendar.getInstance()is non-null, so the return value is guaranteed non-null. That's why this method isn't flagged.testGregorianCalendar2(): This is where the older analyzer's limitation shows up. ThesetTimeZone2()method has an explicit branch that returnsnullif its input isnull. Even though you're passing a non-null value to it in this specific call, SonarQube 6.7.1's flow analysis can't track that the null branch is unreachable here.
The analyzer treats setTimeZone2() as a method that could return null (because its signature lacks @Nonnull, and it has a null return path) — regardless of the actual input in this invocation. Since testGregorianCalendar2() is annotated with @Nonnull, the rule flags it because it sees a potentially null-returning method being used as the return value of a non-null guaranteed method.
Key takeaway
This is a static analysis limitation specific to SonarQube 6.7.1 LTS. Newer versions of SonarQube have significantly improved flow tracking that can recognize the null branch in setTimeZone2() isn't hit when passing a non-null input, so they wouldn't flag this case as a violation.
内容的提问来源于stack exchange,提问作者Tobias Barth

