java:S1612: false positive with generics

Product : SonarCloud

Analyzer running on JDK11
Project source: Java8
CI: Jenkins
Build: Maven3

java:S1612 is suggesting replacing the lambda e -> (E) e by E.class::cast.
However it’s not possible because E is a generic type and E.class cannot be compiled.

package fpreproducer;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import lombok.AccessLevel;
import lombok.Getter;

public class EntityCollector {
	private static final Map<Class<?>, EntityCollector> entityCollectors = new LinkedHashMap<>();
	@Getter(AccessLevel.PRIVATE)
	private final List<Entity<?>> collection = new ArrayList<>();

	@SuppressWarnings("unchecked")
	public static <E extends Entity<E>> void someMethod( final Class<E> clazz ) {
		entityCollectors.get(clazz).getCollection()
				.stream()
				.map( e -> (E) e ) // java:S1612 Lambdas should be replaced with method references 
				;
	}

	class Entity<T> {
		@SuppressWarnings("unused")
		private T field;
	}
}
1 Like

Hi,

Just to check, are you using sonar.java.source=8 in your analysis parameters to tell the analysis that you’re writing Java 8 code?

 
Thx,
Ann

Hi!

@ganncamp we don’t have this parameter set explicitly, however the log of the Jenkins job contains this info:

[INFO] 19:05:40.343 Sensor JavaSensor [java]
[INFO] 19:05:40.726 Configured Java source version (sonar.java.source): 8
[INFO] 19:05:40.733 JavaClasspath initialization
[DEBUG] 19:05:40.735 Property 'sonar.java.jdkHome' set with: ..../slave/tools/jdk-11.0.2

so it may be implied from the pom.xml maven-compiler-plugin java-version configuration?

Hi,

Yes! This is being read from your POM & that’s perfect.

And at this point, I’m out of my depth, but a language specialist should be along to look at this.

 
Ann

1 Like

Hi, I created the following SONARJAVA-4203 ticket to remove the false-positive. Unfortunately, if you have a false-positive, it means the java analyzer has an unknown symbol E and from what you report I can not understand.

2 Likes