I'm trying to write a Map
builder. One of the constructors will allow the client to specify the type of Map
they wish to build
public class MapBuilder<K, V> {
private Map<K, V> map;
/**
* Create a Map builder
* @param mapType the type of Map to build. This type must support a default constructor
* @throws Exception
*/
public MapBuilder(Class<? extends Map<K, V>> mapType) throws Exception {
map = mapType.newInstance();
}
// remaining implementation omitted
}
The intent is that it should be possible to construct instances of the builder with:
MapBuilder<Integer, String> builder = new MapBuilder<Integer, String>(LinkedHashMap.class);
or
MapBuilder<Integer, String> builder = new MapBuilder<Integer, String>(HashMap.class);
It seems that the type signature of the constructor argument doesn't currently support this, because the line above causes a "Cannot resolve constructor" compilation error.
How can I change my constructor so that it accepts classes that implement Map
only?