猿问

将泛型 Class 参数限制为实现 Map 的类

我正在尝试编写一个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仅实现的类?


皈依舞
浏览 190回答 3
3回答

拉风的咖菲猫

使用 aSupplier而不是 a Class:public MapBuilder(Supplier<? extends Map<K, V>> supplier) {&nbsp; &nbsp; map = supplier.get();}然后可以这样调用:MapBuilder<Integer, Integer> builder = new MapBuilder<>(LinkedHashMap::new);这也更安全,因为 aClass<Map> 可能没有默认构造函数,这会引发错误(响应速度不是很快)

FFIVE

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

慕哥6287543

以下将起作用:public MapBuilder(Class<? extends Map> mapType) throws Exception {&nbsp; &nbsp; map = mapType.newInstance();}
随时随地看视频慕课网APP

相关分类

Java
我要回答