有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何解决java泛型引起的ClassCastException

大多数人都经历了由java泛型引起的ClassCastException。大家都知道这是因为Java泛型擦除,但我们应该如何解决这个问题呢?例如:

Map<Integer,Long> map = new HashMap<>();
map.put(1,0L);

// I know this way violates the java generic constraint.
String json = JSONUtils.toJSONString(map);
Map<Integer,Long> mapFromJson = JSONUtils.parseMap(json);

for(Long v : mapFromJson.values()){
     // will throw ClassCastException
     System.out.println(v);
}

java通用约束太多了,所以我在使用它时必须小心。为什么java不使用C++之类的真正的泛型?


共 (1) 个答案

  1. # 1 楼答案

    虽然存在Java泛型擦除,但我们知道泛型是什么,所以我们可以用jackson这样解决它

        @Test
        void 测试() {
            Map<Integer,Long> map = new HashMap<>();
            map.put(1,0L);
    
            String json = null;
            try {
                json = mapper.writeValueAsString(map);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            MapType mapType = mapper.getTypeFactory().constructMapType(map.getClass(), Integer.class, Long.class);
            Map<Integer,Long> mapFromJson = null;
            try {
                mapFromJson = mapper.readValue(json,mapType);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            for(Long v : mapFromJson.values()) {
                // will not throw ClassCastException
                System.out.println(v);
            }
        }
    

    也许是一种更好的方式,因为你可以直接复制类型:

        @Test
        void 测试() {
            Map<Integer,Long> map = new HashMap<>();
            map.put(1,0L);
    
            // I know this way violates the java generic constraint.
            String json = null;
            try {
                json = mapper.writeValueAsString(map);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            Map<Integer,Long> mapFromJson = null;
            try {
                mapFromJson = mapper.readValue(json, new TypeReference<Map<Integer,Long>>(){});
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            for(Long v : mapFromJson.values()) {
                // will throw ClassCastException
                System.out.println(v);
            }
        }