泛型 exception ****has the erasure as****

本文探讨了Java泛型在实现接口时遇到的问题,特别是在Eclipse编译器与Javac的不同表现下,对于方法覆写的理解差异。通过具体的代码示例,分析了编译器如何处理泛型方法的覆写,并讨论了语言规范对此类情况的规定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

泛型用了很久,只知道一些常识...很多的细节没有搞清楚...

今天使用Eclipse写泛型的时候碰到了情况

与http://www.iteye.com/problems/7602相似
public interface I<X> {   
public void query(Map <String, Object> map, int count);
}
public class C implements I {
public void query(Map <String, Object> map, int count) {}
}

这样子写,编译不通过...
提示错误:
****has the erasure as****


[quote]关键是两者的编译器实现不同。上面的程序可以直接在命令行用javac编译通过,所以我估计jdeveloper使用的编译器就是javac。我以前也一直认为eclipse也是直接使用javac编译器,刚才查看了eclipse插件目录下org.eclipse.jdt.core.jar,里面包括词法分析器,语法解析器,编译器,我才确定eclipse使用了自己的编译器。至于netbeans没有研究,应该也是使用了自己的编译器。

p.s. 在Eclipse下如果接口I中不带任何方法或者方法签名中不使用泛型,则不会出错误。

to feng_gladys:从eclipse提示的错误:
Name clash: The method query(Map<String,Object>, int) of type C has the same erasure as query(Map, int) of type I but does not override it

这样解释也合乎情理,但是从语言规范上来说应该是容许这种情况发生的,不应该有任何错误,至多也只是警告,不过提示错误也未尝不是坏事。[/quote]

以下这段话是 The Java Programming Language 中描述overridding的:

A method in a subtype potentially overrides an accessible method in a super type if the two methods have the same name and have override-equivalent signatures. We say "potentially overrides" because there is an additional requirement to be met: The signature of the subclass method must be the same as that of the superclass method, or it must be the same as the erasure of the signature of the superclass method. This constraint makes overriding a "one-way street": [color=red]A method without generic types can override a method with generic types, but not the other way around.[/color]

上面就改成
public interface I<X> {   
public void query(Map <String, Object> map, int count);
}
public class C implements I {
public void query(Map map, int count) {}
}


----------------------------------------
但是当这样写的时候:

public interface I<X> {   
public void query(Map <String, Object> map, int count);
}
public class C implements I <X>{
public void query(Map <String, Object> map, int count) {}
}

子类中的方法与父类的方法就必须一样,否则也出错...

更多的细节还有待学习...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值