After going through the following links i.e. link1 and link2, i am facing a challenge to provide a class literal as a parameter. Following is my code and i am getting compile error as follows:
class GenericService {
public <T> List<T> serve(Class<T> clazz) {
if(clazz == Set.class) {
Set<String> inputs = new HashSet<>();
return implement(inputs, clazz);
} else if(clazz == Map.class) {
Map<String, Object> inputs = new HashMap<>();
return implement(inputs, clazz);
}
}
public List<Set<String>> implement(Set<String> inputs, Type clazz) {
//Based on clazz decide that the output will be of type 'List<Set<String>>'
List<Set<String>> result = new ArrayList<>();
//do something with inputs
//populate result
return result;
}
public List<Map<String, Object>> implement(Map<String, Object> inputs, Type clazz) {
//Based on clazz decide that the output will be of type 'List<Map<String, Object>>'
List<Map<String, Object>> result = new ArrayList<>();
//do something with inputs
//populate result
return result;
}
}
Couple of things to be noticed:
- I can only pass
List.class
orMap.class
instead of also specifying the generic type. Based on that the result type is determined (implementation details are not provided). - Since, the result type is derived using
class literal
i am getting the following compile time errors.
Type mismatch: cannot convert from List<Set<String>> to List<T>
Type mismatch: cannot convert from List<Map<String,Object>> to List<T>
How can i get this to work ?
>> response = (ResponseEntity
– ernest_k Apr 08 '19 at 08:24>>) gasRestClient.postEntity(uri, List.class, serviceRequestDTO);`. This will be an unchecked cast, so you'd have to live with that warning.