Java Generics with Class

后端 未结 6 2158
Happy的楠姐
Happy的楠姐 2020-12-31 16:03

So I have a map:

Map format = new HashMap();

And I would add elements to it like this:



        
6条回答
  •  礼貌的吻别
    2020-12-31 16:37

    Change:

    Class type = Integer.class
    Integer i = verifyType("100",type);
    

    to

    Class type = Integer.class
    Integer i = verifyType("100",type);
    

    By only declaring the type as 'Class', you're losing the generic parameter and the verifyType() method can't infer the class, thus the unchecked warning.

    This problem:

    Map format = new HashMap();
    format.put("Vendor Number", Integer.class);
    format.put("Vendor Dispatch", Date.class);
    Integer i = verifyType("100",format.get("Vendor Number"));
    

    can't really be solved due to type erasure. The compiler can't infer the type based on a generic parameter that is gone by runtime. This is because Java generics are little more than smoke and mirrors for casting.

提交回复
热议问题