简体   繁体   中英

Generic parametric return value in generic methods

I'm writing a wrapper for JSON Jackson pojo serialization/deserialization. So I tried to write a generic method that will return me the deserialized object generically.

I think the code would explain this better:

public <K,V, M extends Map<K, V>> M readMap(String path, Class<M> mapType, Class<K> keyClass, Class<V> valueClass) throws JsonParseException, JsonMappingException, IOException
{
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(new File(path), mapper.getTypeFactory().constructMapType(mapType, keyClass, valueClass));
}

The code

HashMap<String, Double> weightMap;
JSONParsedFileHandler reader = new JSONParsedFileHandler();
weightMap = reader.readMap("weights.model", HashMap.class, String.class, Double.class);

This works as expected, however, I get a type safety warning:

Type safety: The expression of type HashMap needs unchecked conversion to conform to HashMap<String,Double>

I figured this mean that the type returned is as expected except it is not parameterized as I coded.

Does anyone have any thoughts?

The constructMapType method returns MapType , which uses Class<?> to define the keys and the content. With type erasure that basically translates to Object and there is no way for the compiler to tell what types are used in the map. The type is "parameterized as (you) coded", but Java's implementation of generics prevents any run-time knowledge of the type that you provided. Someone correct me if I'm wrong, but I believe you're only options are to deal with the warning or suppress it.

Try bounding to just the maps's class and declare the return type from K and V only:

public <K,V, M extends Map<?, ?>> Map<K, V> readMap(String path, Class<M> mapClass, Class<K> keyClass, Class<V> valueClass) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(new File(path), mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM