What I would like to obtain is something that can safely return the instance of an input class. In my case is used as a service provider. A code sample:
public class MyClass {
private Map<String, Object> mServices;
public MyClass() {
mServices = new HashMap<String, Object>();
mServices.put(XmlService.class.getName(), new XmlService());
}
public <E extends Object> E getService(Class<?> service) {
return (E) mServices.get(service.getName());
}
}
I admit that I am not that skilled with Parameterized Types and I need some help here. Am I not getting an Object from the Map? Why do I need to cast to E, loosing the type safety? Is there a way to avoid either casting and/or suppress warnings?
No, unfortunately the is no way to avoid this extra downcast. Notice that the type of your map is Map<String, Object>
. Object
- that is all the Java compiler knows about values. You would have to somehow declare the map to have different type of every key. Impossible.
But your code can be simplified a bit:
public <E> E getService(Class<E> service) {
return (E) mServices.get(service.getName());
}
Another slight improvement involves using Class
as key:
private Map<Class<?>, Object> mServices;
public <E> E getService(Class<E> service) {
return (E) mServices.get(service);
}