简体   繁体   中英

Java: (false?) positive S2637 in SonarQube 6.7.1 LTS

I am using SonarQube 6.7.1 LTS on a Java project and I analyze it using Maven sonar plugin.

I have the following code example, which finds an S2637 issue in method testGregorianCalendar2 :

public static final @Nonnull Calendar testGregorianCalendar1() {
    return GregorianCalendar.getInstance();
}

public static final @Nonnull Calendar testGregorianCalendar2() {
    return setTimeZone2(GregorianCalendar.getInstance());
}

public static final Calendar setTimeZone2(final Calendar inputCalendar) {
    if (null == inputCalendar) {
        return null;
    }
    return inputCalendar;
}

public static final @Nonnull Calendar testGregorianCalendar3() {
    return setTimeZone3(GregorianCalendar.getInstance());
}

public static final Calendar setTimeZone3(final Calendar inputCalendar) {
    return inputCalendar;
}

In the methods testGregorianCalendar1 and testGregorianCalendar3 , that issue is not found by Sonar. I think in testGregorianCalendar2 , it should also not be found, or it should be found in all 3 methods testGregorianCalendar* , because:

Sonar should decide for itself, if GregorianCalendar.getInstance() can return null or not. If yes, all 3 methods can return null and Sonar should find the issue in all of these methods.

If no, then the method setTimeZone2 is called with a non-null value, and it will then return a non-null value, so testGregorianCalendar2 will return a non-null value.

What is going wrong there?

I don't know for sure, but here's what I would guess is happening: setTimeZone2 has a conditional return null , therefore returning the return value from setTimeZone2 from a @Nonnull method is not allowed without a check for that null value.

That is, the analyzer sees:

public static final Calendar setTimeZone2(final Calendar inputCalendar) {
    if (/* something */) {
        return null;
    }
    return /* null if inputCalendar is null */;
}

And it determines: the return value of setTimeZone2 is (potentially) @Nullable .

Then it sees:

public static final @Nonnull Calendar testGregorianCalendar2() {
    return setTimeZone2(/* something */);
}

And it sees a potentially @Nullable value being returned from a method marked @Nonnull , which produces a warning.

You and I can reason that setTimeZone2 will never return null unless inputCalendar is null, and that inputCalendar can never be null because GregorianCalendar.getInstance() will never return null, but the analyzer probably isn't evaluating under what condition setTimeZone2 can return null, just that it can under some condition.

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