将通用Class参数限制为实现Map的类 [英] Restrict a generic Class parameter to classes that implement Map
问题描述
我正在尝试编写一个Map
构建器.其中一个构造函数将允许客户端指定他们希望构建的Map
的类型
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.
如何更改构造函数,使其接受仅实现Map
的类?
How can I change my constructor so that it accepts classes that implement Map
only?
推荐答案
使用Supplier
代替Class
:
public MapBuilder(Supplier<? extends Map<K, V>> supplier) {
map = supplier.get();
}
然后可以这样称呼它:
MapBuilder<Integer, Integer> builder = new MapBuilder<>(LinkedHashMap::new);
这也更安全,因为Class<Map>
可能没有默认构造函数,这会引发错误(代码响应性不强)
This is also safer, because a Class<Map>
could have no default constructor, which would throw an error (which is not very responsive code)
这篇关于将通用Class参数限制为实现Map的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!