代码之家  ›  专栏  ›  技术社区  ›  Raildex

继承具有指定类型的泛型类时是否发生类型擦除?

  •  2
  • Raildex  · 技术社区  · 6 年前

    当我有一个 List<Foo> ,它将变成 List 在编译时由于类型擦除。

    但是如果我用

    class FooList extends List<Foo>
    

    ?
    是我的 FooList 一览表 Foo 或一览表 Object 在编译时?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ronaldo Lanhellas    6 年前

    必须注意以下几点:

    1. 一个班级不能 extends 因为它是一个接口,所以您应该 implements 在这种情况下。
    2. 生成项目后,字节码(.class文件)应如下所示: public abstract class FooList implements List<Foo> ,所以这是一个简单的foo列表。
    3. 小心使用这种方法,使用您的傻瓜和简单的列表来查看这种代码:

      公共类主{

      public static void main(String[] args) {
      
         //works
         List<Foo> foos = new ArrayList<>();
      
         //don't work
         FooList fooList = new ArrayList<>();
         FooList fooList2 = new ArrayList();
      
         //work, but not necessary
         FooList fooList3 = new FooList() {
             //implement all method from List interface
         };
      }
      

      }