SonarQube 9.1
The detection of the immutability of classes fails on some classes (in particular collections)
and java:S2386: Mutable fields should not be “public static” is improperly triggered.
example:
import java.util.AbstractList;
import java.util.List;
import javax.annotation.concurrent.Immutable;
public class Test {
private Test() { }
// ERROR -> This immutable static final fields triggers:
// java:S2386: Mutable fields should not be "public static"
public static final List<Object> WRONG_IMMUTABLE_FIELD = new ImmutableList<>();
// OK -> This immutable field is properly detected and the rule java:S2386 is not triggered
public static final List<Object> OK_IMMUTABLE_FIELD = List.of("P1");
// OK -> This immutable field is properly detected and the rule java:S2386 is not triggered
public static final OtherImmutableClass OK_IMMUTABLE_FIELD2 = new OtherImmutableClass();
@Immutable
public static class ImmutableList<T> extends AbstractList<T> {
@Override public T get(int index) { return null; }
@Override public int size() { return 0; }
@Override
public String toString() { return "This class is NOT properly detected as immutable"; }
}
public static class OtherImmutableClass {
@Override
public String toString() { return "This class is properly detected as immutable"; }
}
}