In Java, why is there no generic type info at run time?

后端 未结 3 1967
悲&欢浪女
悲&欢浪女 2020-12-16 05:10

Consider this example taken from a book, with a super class Gen and a subclass Gen2...

class Gen { }

class Gen2 extends Gen { }
<         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 05:55

    You have "overlooked a simple concept". The generics exist only at compile time, and only to enforce things like parametric polymorphism. Because the folks who implemented them decided that developers should be able to use them (generics) and still deploy their built artifacts to targets with older JVMs (an extremely questionable decision in my mind, as the runtime libraries also changed between 1.4 and 1.5), they had the compiler decide if everything type-checks and then they throw away almost all of that information before creating the compiled artifact.

    I say almost all of that information because in some special cases it is still around at runtime.

提交回复
热议问题