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

后端 未结 6 1019
自闭症患者
自闭症患者 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:56

    Of course the information that a class is generic is supported.

    In other words: when you decompile ArrayList.class you will find hints about the fact that this class allows for one generic type parameter. In other words: class files contain meta information. And using reflection it is possible to inspect this meta information at runtime.

    But when you have another class that uses some List object - then you do not find information about that "list uses an Integer" in the compiled class - unless you use some specific patterns, as outlined here for example.

    So the answer is basically: for almost all use cases of practical relevance, "generics" are compile time only.

    Example:

    public class GenericsExample {
      private T member;   
      public T foo(T bar) {
         return member;
      }
    }
    

    Now run: javap -p -c GenericsExample

    Compiled from "GenericsExample.java"
    public class GenericsExample {
      private T member;
    
      public GenericsExample();
        Code:
           0: aload_0       
           1: invokespecial #1                  // Method java/lang/Object."":()V
           4: return        
    
      public T foo(T);
        Code:
           0: aload_0       
           1: getfield      #2                  // Field member:Ljava/lang/Object;
           4: areturn       
    }
    

    As you can see the decompiler understands that the class uses that generic type T. For more details see here or there.

提交回复
热议问题