I would like to have a map with the class type as a key in order to avoid casting when accessing the value.
Update
The following is actual code you can copy/paste in an IDEA and reproduce it.
interface MyInterface {
}
class SomeConcreteClass implements MyInterface{
}
private Map<Class<?>, ? extends MyInterface> map = newMap();
private Map<Class<?>, ? extends MyInterface> newMap() {
Map<Class<?>, ? extends MyInterface> map = new HashMap<>();
map.put(SomeConcreteClass.class, new SomeConcreteClass());
return map;
}
private void accessMap() {
SomeConcreteClass clazz = (SomeConcreteClass) map.get(SomeConcreteClass.class); <== I want to avoid cast here
}
Problem: This does not compile. I get in this line:
map.put(SomeConcreteClass.class, new SomeConcreteClass());
the error:
Wrong 2nd argument type. Found: 'SomeConcreteClass required '? extends MyInterface`
What am I doing wrong here? SomeConcreteClass
should be accepted as it implements the interface