泛型

作者: canezk | 来源:发表于2016-11-11 17:32 被阅读6次

    类型擦除

    今天同事遇到个问题,好好看了下泛型这块
    
    • java的泛型比较重要的一点是类型擦除。避免生成多个class文件
      ** 例子 **
    (忽略代码规范
    public class testTypeErase {
     
     private class Base {
      
      protected <T> T test(TypeRefer typeRefer) {
       T t = null;
       return t;
      }
     }
     
     private class TypeRefer<T> {
      //private final Class<T> type;
    
      T value;
          public TypeRefer(T value) {
           this.value = value;
          }
    
          public void getValue() {
           System.out.println((String)value);
          }
     }
     
     private class Child<T> extends Base {
      private T value;
      public Child(T value) {
       this.value = value;
      }
      public T testChild() {
       TypeRefer ty = new TypeRefer<T>(value);
       ty.getValue();
       T t = null;
       return t;
      }
     }
    

    ** javap看字节码头 **

    class test.zk.generic.testTypeErase$Child<T> extends test.zk.generic.testTypeErase$Base {
      final test.zk.generic.testTypeErase this$0;
    
      public test.zk.generic.testTypeErase$Child(T);
        Code:
           0: aload_0
           1: aload_1
           2: putfield      #15                 // Field this$0:Ltest/zk/generic/testTypeErase;
           5: aload_0
           6: aload_1
           7: aconst_null
           8: invokespecial #17                 // Method test/zk/generic/testTypeErase$Base."<init>":(Ltest/zk/generic/testTypeErase;Ltest/zk/generic/testTypeErase$Base;)V
          11: aload_0
          12: aload_2
          13: putfield      #20                 // Field value:Ljava/lang/Object;
          16: return
    
      public T testChild();
        Code:
           0: new           #31                 // class test/zk/generic/testTypeErase$TypeRefer
           3: dup
           4: aload_0
           5: getfield      #15                 // Field this$0:Ltest/zk/generic/testTypeErase;
           8: aload_0
           9: getfield      #20                 // Field value:Ljava/lang/Object;
          12: invokespecial #33                 // Method test/zk/generic/testTypeErase$TypeRefer."<init>":(Ltest/zk/generic/testTypeErase;Ljava/lang/Object;)V
          15: astore_1
          16: aload_1
          17: invokevirtual #35                 // Method test/zk/generic/testTypeErase$TypeRefer.getValue:()V
          20: aconst_null
          21: astore_2
          22: aload_2
          23: areturn
    

    参考

    泛型 oracle
    泛型 类型擦除

    相关文章

      网友评论

          本文标题:泛型

          本文链接:https://www.haomeiwen.com/subject/ompfpttx.html