Restrict a generic Class parameter to classes that implement Map

  • A+

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


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?


Use a Supplier instead of a Class:

public MapBuilder(Supplier<? extends Map<K, V>> supplier) {     map = supplier.get(); } 

Which then can be called like this:

MapBuilder<Integer, Integer> builder = new MapBuilder<>(LinkedHashMap::new); 

This is also safer, because a Class<Map> could have no default constructor, which would throw an error (which is not very responsive code)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: