Как решить ClassCastException, вызванную обобщением Java

foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    ((TextBox)x).Text = String.Empty;
//instead of above line we can use 
     ***  x.resetText();
  }
}
-2
задан Tom 18 January 2019 в 02:47
поделиться

1 ответ

Думал, что существует универсальное стирание Java, но мы знаем, что такое универсальный, поэтому мы можем решить его таким образом с Джексоном.

    @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);
        }
    }
0
ответ дан Sando Geek 18 January 2019 в 02:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: