java 重载方法:两种方法具有相同的擦除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43442515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overloading a method: both methods have same erasure
提问by parsecer
I have the following code and it doesn't work: the error both methods have same erasure
appears.
我有以下代码但它不起作用:both methods have same erasure
出现错误。
public class Foo<V> {
public static void main(String[] args) {
}
public void Bar(V value) {
}
public void Bar(Object value) {
}
}
Also I have this code:
我也有这个代码:
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 {
}
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?
这有效。在第一种情况下V
是 的孩子Object
,就像在第二种情况下B
是 的孩子一样A
。那为什么第一种情况会出错,而第二种情况编译成功呢?
EDIT: What should I do to achieve method overloading, without raising an error?
编辑:我应该怎么做才能实现方法重载而不引发错误?
回答by Andy Turner
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.
简单:不要尝试使用具有相同擦除的参数重载方法。
A few options:
几个选项:
- 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 needthose 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>
- 只需给方法不同的名称(即不要尝试使用重载)
- 向重载之一添加更多参数,以允许消除歧义(理想情况下,仅在您确实需要这些参数时才这样做;但 Java API 中有一些示例,其中存在垃圾参数只是为了避免重载问题)。
按照@Kayaman 的建议绑定类型变量:
<V extends SomethingOtherThanObject>
回答by Kayaman
V
isn't "a child of Object
". V
is an unbounded generic type that erases to Object
, resulting in the error. If the generic type were bounded, such as <V extends Comparable<V>>
, it would erase to Comparable
and you wouldn't get the error.
V
不是“的孩子Object
”。V
是一个无界泛型类型,它擦除为Object
,从而导致错误。如果泛型类型是有界的,例如<V extends Comparable<V>>
,它将擦除到Comparable
并且您不会收到错误。