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

后端 未结 1 653
难免孤独
难免孤独 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<List<Integer>> tListInt3 = 
                (Class<List<Integer>>) ((Class<Integer>)List.class);
    

    that doesn't work. you probably meant

    Class<List<Integer>> tListInt3 = 
                (Class<List<Integer>>) ((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<List>; it is not a subtype/supertype of Class<List<Whatever>> therefore direct cast between the two types is illegal.

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

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

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