【问题标题】:Java override constructor using List<CustomObjects> - "same erasure" errorJava 使用 List<CustomObjects> 覆盖构造函数 - “相同擦除”错误
【发布时间】:2018-12-13 03:29:40
【问题描述】:

您好,我想重写自定义类 MyList 中的构造函数。

下面的代码可以编译,我收到“相同的擦除”错误。对于编译器List&lt;CustomClass1&gt;List&lt;CustomClass2&gt; 的类型相同

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

private static class MyList {

    private int type;

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

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

    }
}

【问题讨论】:

标签: java generics


【解决方案1】:

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

当泛型类型被实例化时,编译器会翻译那些 类型通过一种称为类型擦除的技术——一个过程,其中 编译器删除与类型参数和类型相关的所有信息 类或方法中的参数。类型擦除启用 Java 使用泛型来保持二进制兼容性的应用程序 在泛型之前创建的 Java 库和应用程序。

【讨论】:

    【解决方案2】:

    java 编译器“擦除”类型参数。所以List&lt;CustomClass1&gt;List&lt;CustomClass2&gt;在类型擦除后变成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) {
            // ...
        }
    }
    

    【讨论】:

    • tnx 为您解答,但我如何检查列表类型(CustomClass1CustomClass2)?我尝试使用 ` if (list.getClass().equals(CustomClass1.class)) {` 但这不起作用
    • @Jovan:如果您将Class 作为参数传递,您可以添加一个返回此值的方法getClazz() 并几乎像往常一样使用list.getClazz().equals(CustomClass1.class)
    • @Jovan:也许很有趣stackoverflow.com/questions/6624113/…
    猜你喜欢
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多