Java casting “.class”-operator used on a generic type, e.g. List, to “Class” and to “Class>”

后端 未结 1 659
难免孤独
难免孤独 2020-12-03 11:04

I use the .class-operator to supply information about the contained type to a generic class. For non-generic contained types, e.g. Integer.class,

1条回答
  •  渐次进展
    2020-12-03 11:25

    Class> tListInt3 = 
                (Class>) ((Class)List.class);
    

    that doesn't work. you probably meant

    Class> tListInt3 = 
                (Class>) ((Class)List.class);
    

    we can always cast from one type to another by up-cast then down-cast

        Integer x = (Integer)(Object)"string";
    

    The type of List.class is Class; it is not a subtype/supertype of Class> therefore direct cast between the two types is illegal.

    It can be argued that Class> doesn't exist - there is only a class for List; there is no such class for List (which really is just List at runtime)

    However, this is a flaw of Java type system; in practice we do need things like Class>. Our solution - casting and pretending Class> exits - is likewise flawed - but it's not our fault.

    0 讨论(0)
提交回复
热议问题