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

后端 未结 6 894
自闭症患者
自闭症患者 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 06:37

    Is there any information related to generic types which is preserved at runtime as well. ? If yes, what ?.

    Single information preserved in the compiled class, are casts from raw objects/variables gotten after erasure to the specific types used as generic in the source code.
    But these rely just on the declared type of variable, not the real generic type used.

    So, at runtime you cannot directly access to the generic information without workaround as passing a class when you instantiate a generic class.

    If no, than how does libraries like google guice operate internally (

    You are wrong.
    In Guice this code :

     Content content = contentProvider.get();   
    

    will return an instance of Content, not the generic type. Look at the documentation :

    T get()

    Provides an instance of T.

提交回复
热议问题