I have a code example where Java forces me to use the extends
keyword on a class that is final in a PECS construction. I do not understand why exactly. The code can be found below or at https://onecompiler.com/java/3yvf4g97f. The compiler fails to compile method named process
. If I remove method process
then SonarLint will trigger a violation of rule https://rules.sonarsource.com/java/RSPEC-4968 for method named processPecs
. Which seems reasonable, or is this a false positive? Is there a better approach for "processing arbitrary data"? Do I need to suppress SonarLint's warning here and file a bug report for SonarLint?
import java.util.List;
class PecsTest {
static final class DataContainer<D> {
final D data;
public DataContainer(D data) {
this.data = data;
}
D getData() {
return data;
}
}
static class Processor<D> {
@SuppressWarnings("unchecked")
List<DataContainer<D>> processPecs(List<? extends DataContainer<? super D>> list) {
return (List<DataContainer<D>>) list;
}
@SuppressWarnings("unchecked")
List<DataContainer<D>> process(List<DataContainer<? super D>> list) {
return (List<DataContainer<D>>) list;
}
}
static class Data {
}
static class ExtendedData extends Data {
}
public static void main(String[] args) {
new Processor<Data>().processPecs(List.of(new DataContainer<>(new ExtendedData())));
new Processor<ExtendedData>().processPecs(List.of(new DataContainer<>(new Data())));
}
}