简体   繁体   中英

Storing abstract and concrete types in Map

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?

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM