使用 List 的 Java 覆盖构造函数<CustomObjects> - "same erasure"错误



嗨,我想在自定义类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;
    }
}

由于所谓的类型擦除,泛型类型信息在编译期间丢失。当类型信息被擦除时,两者都编译为public MyList(List l)。这就是Java的工作方式。泛型只在编译时可用。

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

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) {
        // ...
    }
}

相关内容

最新更新