重载方法:两种方法具有相同的擦除 [英] Overloading a method: both methods have same erasure

查看:30
本文介绍了重载方法:两种方法具有相同的擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码但它不起作用:出现错误两种方法具有相同的擦除.

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  {
}

这是有效的.在第一种情况下 VObject 的孩子,就像在第二种情况下 BA 的孩子一样>.那为什么第一种情况会出错,而第二种情况却编译成功呢?

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.

几个选项:

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

  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 need those 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>

这篇关于重载方法:两种方法具有相同的擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆