我正在尝试编写一个Map构建器。其中一个构造函数将允许客户端指定Map他们希望构建的类型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}目的是应该可以通过以下方式构造构建器的实例:MapBuilder<Integer, String> builder = new MapBuilder<Integer, String>(LinkedHashMap.class);或者MapBuilder<Integer, String> builder = new MapBuilder<Integer, String>(HashMap.class);似乎构造函数参数的类型签名当前不支持这一点,因为上面的行会导致“无法解析构造函数”编译错误。如何更改我的构造函数以使其接受Map仅实现的类?
3 回答

拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
使用 aSupplier而不是 a Class:
public MapBuilder(Supplier<? extends Map<K, V>> supplier) {
map = supplier.get();
}
然后可以这样调用:
MapBuilder<Integer, Integer> builder = new MapBuilder<>(LinkedHashMap::new);
这也更安全,因为 aClass<Map> 可能没有默认构造函数,这会引发错误(响应速度不是很快)

FFIVE
TA贡献1797条经验 获得超6个赞
问题LinkedHashMap.class
是
Class<LinkedHashMap>
而不是像
Class<LinkedHashMap<Integer, String>>
这些也是不可转换的类型(所以你不能转换它)并且没有办法获得后者的实例。
您可以做的是将构造函数更改为
public MapBuilder(Class<? extends Map> mapType) throws Exception
泛型在运行时被删除,所以在运行时所有Map
的 s 都会表现得像Map<Object, Object>
无论如何。因此,您构建的类是否使用原始类型并不重要。
顺便说一句,Class::newInstance
已弃用。利用
mapType.getConstructor().newInstance()

慕哥6287543
TA贡献1831条经验 获得超10个赞
以下将起作用:
public MapBuilder(Class<? extends Map> mapType) throws Exception {
map = mapType.newInstance();
}
添加回答
举报
0/150
提交
取消