Rule S2118: false positive because the concrete type can easily be inferred from the variable declaration

java

(phermsdorf) #1

Hi,

code sample:

// member definition 
private final Map<Integer, List<Object>> cache = new HashMap<>();

// usage with serialization
		try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
			oos.writeObject(cache);
		} catch (final Exception e) {
			e.printStackTrace();
		}

leads to “Non-serializable classes should not be written” because the interface Map does not implement Serializable but HashMap does. To fix this issue one would need to define the member cache as:

private final HashMap<Integer, List<Object>> cache = new HashMap<>();

And since the conrete type of the member cache can be inferred by the source code i think this is a false positive.

We use SonarQube 7.5 with latest Java analyzer.

Thanks for looking at the issue.