你好,我想覆盖自定义类MyList中的构造函数。
下面的代码可以编译,我收到"same erasure“错误。对于编译器,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;
}
}发布于 2011-11-08 05:05:06
这是因为所谓的擦除类型擦除( the generic type information is lost during compilation )。当类型信息被擦除时,两者都会向下编译为public MyList(List l)。这就是Java的工作方式。泛型仅在编译时可用。
当泛型类型被实例化时,编译器通过一种称为类型擦除的技术转换这些类型-在这个过程中,编译器删除与类或方法中的类型参数和类型参数相关的所有信息。类型擦除使使用泛型的Java应用程序能够保持与泛型之前创建的Java库和应用程序的二进制兼容性。
发布于 2011-11-08 05:05:43
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) {
// ...
}
}https://stackoverflow.com/questions/8042561
复制相似问题