Reputation: 105
I have the below code to instantiate all the service on the start of the application. Sonar lint on the IndicesFactory is complaining for generic raw type. What is the best way to fix this?
public class IndicesFactory {
private final Map<String, IndicesStrategy> indicesMap;
public IndicesFactory(List<IndicesStrategy> indicesStrategyList) {
this.indicesMap = new HashMap<>();
indicesStrategyList.forEach(strategy -> this.indicesMap.put(strategy.getOperation().toString(), strategy));
}
private IndicesStrategy getStrategy(String operation) {
return this.indicesMap.get(operation);
}
public <T, R> R execute(String operation, T t) {
return (R) getStrategy(operation).execute(t);
}}
And my IndicesStrategy interface has below code
public interface IndicesStrategy<operation extends Enum<?>, T, R extends
IndicesResponse> {
R execute(T t);
operation getOperation();
}
Upvotes: 0
Views: 165
Reputation: 9482
To get rid of the raw type warnings, values need to be provided for the type parameters of IndicesStrategy
wherever that type is used in IndicesFactory
. It appears that this class needs to handle different types of IndicesStrategy
, so it can use type wildcards (?
) as the values:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class IndicesFactory {
private final Map<String, IndicesStrategy<?, ?, ?>> indicesMap;
public IndicesFactory(List<IndicesStrategy<?, ?, ?>> indicesStrategyList) {
this.indicesMap = new HashMap<>();
indicesStrategyList.forEach(strategy ->
this.indicesMap.put(strategy.getOperation().toString(), strategy));
}
private IndicesStrategy<?, ?, ?> getStrategy(String operation) {
return this.indicesMap.get(operation);
}
public <T, R extends IndicesResponse> R execute(String operation, T t) {
IndicesStrategy<?, T, R> strategy =
(IndicesStrategy<?, T, R>) getStrategy(operation);
return strategy.execute(t);
}
}
As an alternative equivalent, you might prefer to move the unchecked cast into the getStrategy
method:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class IndicesFactory {
private final Map<String, IndicesStrategy<?, ?, ?>> indicesMap;
public IndicesFactory(List<IndicesStrategy<?, ?, ?>> indicesStrategyList) {
this.indicesMap = new HashMap<>();
indicesStrategyList.forEach(strategy ->
this.indicesMap.put(strategy.getOperation().toString(), strategy));
}
private <T, R extends IndicesResponse> IndicesStrategy<?, T, R> getStrategy(String operation) {
return (IndicesStrategy<?, T, R>) this.indicesMap.get(operation);
}
public <T, R extends IndicesResponse> R execute(String operation, T t) {
IndicesStrategy<?, T, R> strategy = getStrategy(operation);
return strategy.execute(t);
}
}
Upvotes: 0