Java Generics : Is any meta information about the generic type preserved at runtime as well?

后端 未结 6 905
自闭症患者
自闭症患者 2021-01-14 06:13

Background

My understanding of Java generics is it being completely a compile time feature (mainly focusing on type safety checks)

6条回答
  •  悲哀的现实
    2021-01-14 07:01

    1. Java Generics uses something called type erasure, so no information about the type is available at runtime. It is, however, possible to create an instance of any class using Class.newInstance() method if the type information can be passed somehow (in fact, this is the only way a generic array could be created)

    2. Compile time safety is the primary goal of generics. But they can often be used to write more concise code as well, which would not have been possible otherwise

    For a detailed treatment, I recommend the excellent book Java Generics and Collections

提交回复
热议问题