Java覆盖构造函数使用List <customobjects> - “相同的擦除”错误</customobjects>

时间:2011-11-07 21:02:15

标签: java generics

您好我想覆盖自定义类MyList中的构造函数。

下面的代码可以编译,我收到“相同的擦除”错误。对于编译器List<CustomClass1>,其类型与List<CustomClass2>

相同

有人可以建议我如何解决这个问题。我尝试使用List<Object>并使用instanceof,但我无法解决这个问题,但没有成功

private static class MyList {

    private int type;

    public MyList (List<CustomClass1> custom1) {
                 type = 1;
    }

    public MyList (List<CustomClass2> custom2) {
                 type = 2;

    }
}

2 个答案:

答案 0 :(得分:1)

因为所谓的类型擦除 the generic type information is lost during compilation。当删除类型信息时,两者都编译为public MyList(List l)。这就是Java的工作原理。泛型仅在编译期间可用。

  

当实例化泛型类型时,编译器会对它们进行转换   通过一种称为类型擦除的技术来进行类型化 - 一种过程   编译器删除与类型参数和类型相关的所有信息   类或方法中的参数。类型擦除启用Java   使用泛型来维护二进制兼容性的应用程序   在泛型之前创建的Java库和应用程序。

答案 1 :(得分:1)

java编译器“擦除”类型参数。因此,List<CustomClass1>List<CustomClass2>在类型删除后变为List(事实上是相同的签名):

public MyList (List list) {
    // ...
}

您可以将类型添加为参数:

public MyList (List<?> list, int type) {
    // ...
}

或者

public MyList (List<?> list, Class<?> clazz) {
    // ...
}

或将类型参数添加到类

class MyList<T> {

    public MyList (List<T> custom2, Class<T> clazz) {
        // ...
    }
}