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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:25:45  来源:igfitidea点击:

Overloading a method: both methods have same erasure

javagenericsjvmjavac

提问by parsecer

I have the following code and it doesn't work: the error both methods have same erasureappears.

我有以下代码但它不起作用: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 Vis a child of Object, just like in the second case Bis 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:

几个选项:

  1. Just give the methods different names (i.e. don't try to use overloading)
  2. 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).
  3. Bound the type variable, as suggested by @Kayaman:

    <V extends SomethingOtherThanObject>
    
  1. 只需给方法不同的名称(即不要尝试使用重载)
  2. 向重载之一添加更多参数,以允许消除歧义(理想情况下,仅在您确实需要这些参数时才这样做;但 Java API 中有一些示例,其中存在垃圾参数只是为了避免重载问题)。
  3. 按照@Kayaman 的建议绑定类型变量:

    <V extends SomethingOtherThanObject>
    

回答by Kayaman

Visn't "a child of Object". Vis 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 Comparableand you wouldn't get the error.

V不是“的孩子Object”。V是一个无界泛型类型,它擦除为Object,从而导致错误。如果泛型类型是有界的,例如<V extends Comparable<V>>,它将擦除到Comparable并且您不会收到错误。