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

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

问题描述

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

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.

一些选项:

  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天全站免登陆