I am trying to determine if it is possible to use Generics in the following situation. It can best be described by my code. (This code is just an example; I took out most of the code not relevant to the problem I'm having.)
public class FooBar {
public <T extends MyModel> Map<Class<T>, List<T>> convertToModelList(
Map<String, Class<T>> infoMap) {
// do stuff...
}
}
public class MyClient {
public void doSomething() {
Map<String, Class<? extends MyModel>> oldMap = new HashMap<String, Class<? extends MyModel>>();
oldMap.put ("car", Car.class);
oldMap.put("truck", Truck.class);
FooBar f = new FooBar();
Map<Class<? extends MyModel>, List<? extends MyModel>> newMap = f
.convertToModelList(oldMap);
}
}
public class Car extends MyModel {
}
public class Truck extends MyModel {
}
public class MyModel {
}
The compiler is saying that I can't call convertToModelList (in MyClient) because a Map<String, Class<? extends MyModel>>
is not equivalent to Map<String, Class<T>>
. I somewhat understand why this is occurring, but is there a way around this?
EDIT:
To be more specific, the problem I'd like to solve is using Generics in the convertToModelList() method above. If I can't use generics here, then whatever I return from that method has to be cast on the client. For example, if I change FooBar to this:
public class FooBar {
public Map<Class<? extends MyModel>, List<? extends MyModel>> convertToModelList(
Map<String, Class<? extends MyModel>> infoMap) {
// do stuff...
}
}
If I pass in a
Map<String, Class<Truck>>
to convertToModelList, it will return a
Map<Class<Truck>, List<Truck>>
, however the client won't know it's a Truck - all it will know is that it's of type MyModel - using generics lets me avoid the cast to Truck in the MyClient code:
public class MyClient {
public void doSomething() {
Map<String, Class<? extends MyModel>> oldMap = new HashMap<String, Class<? extends MyModel>>();
oldMap.put ("car", Car.class);
oldMap.put("truck", Truck.class);
FooBar f = new FooBar();
Map<Class<? extends MyModel>, List<? extends MyModel>> newMap = f
.convertToModelList(oldMap);
// I'm trying to avoid this cast
List<Truck> trucks = (List<Truck>)newMap.get(Truck.class);
}
}