重载方法:两种方法具有相同的擦除 [英] Overloading a method: both methods have same erasure
问题描述
我有以下代码但它不起作用:出现错误两种方法具有相同的擦除
.
I have the following code and it doesn't work: the error both methods have same erasure
appears.
public class Foo<V> {
public static void main(String[] args) {
}
public void Bar(V value) {
}
public void Bar(Object value) {
}
}
我也有这个代码:
public class Foo<V> {
public static void main(String[] args) {
}
public void Bar(B value) {
}
public void Bar(A value) {
}
}
class A {
}
class B extends A {
}
这是有效的.在第一种情况下 V
是 Object
的孩子,就像在第二种情况下 B
是 A
的孩子一样>.那为什么第一种情况会出错,而第二种情况却编译成功呢?
And this works. In the first case V
is a child of Object
, just like in the second case B
is a child of A
. Then why the first case results in error, while the second compiles successfully?
编辑:我应该怎么做才能实现方法重载而不引发错误?
EDIT: What should I do to achieve method overloading, without raising an error?
推荐答案
我应该怎么做才能实现方法重载而不引发错误?
What should I do to achieve method overloading, without raising an error?
简单:不要尝试使用具有相同擦除的参数重载方法.
Simple: don't try to overload the method with parameters with the same erasure.
几个选项:
- 只需给方法不同的名称(即不要尝试使用重载)
- 向重载之一添加更多参数,以消除歧义(理想情况下,只有在您确实需要这些参数时才这样做;但 Java API 中有一些示例,其中存在垃圾参数只是为了避免超载问题).
按照 @Kayaman 的建议绑定类型变量:
- Just give the methods different names (i.e. don't try to use overloading)
- Add further parameters to one of the overloads, to allow disambiguation (ideally only do this if you actually need those parameters; but there are examples in the Java API where there are junk parameters simply to avoid overloading issues).
Bound the type variable, as suggested by @Kayaman:
<V extends SomethingOtherThanObject>
这篇关于重载方法:两种方法具有相同的擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!