Reputation: 726
I have an interface and class like following:
public interface Message extends Wrappable
{
}
public class MessageImpl implements Message
{
}
I want to use Java generics to store these Classes into a Map with interface as key and impl as value as:
map.put(Message.class, MessageImpl.class);
I want it to be typesafe, where key must extends Wrappable and value must extend key class. Any help on this?
Upvotes: 2
Views: 577
Reputation: 198033
A basic Map
can't do this type safely, but you can create a simple wrapper around a Map
to enforce type safety. That might look something like
class MyMap {
private final Map<Class<?>, Class<?>> map = new HashMap<>();
public <A extends Wrappable, B extends A> void put(
Class<A> interfaceClass, Class<B> implClass) {
// you can't statically enforce that A is an interface
// and B is a concrete class, though you can do it at runtime
assert interfaceClass.isInterface();
assert !Modifier.isAbstract(implClass.getModifiers());
map.put(interfaceClass, implClass);
}
public <A extends Wrappable> Class<? extends A> get(Class<A> interfaceClass) {
return (Class<? extends A>) map.get(interfaceClass);
}
}
Upvotes: 4