方法重载
我想知道你是否可以在这里提出一些建议。
我想要两种方法:
doSomething(List<Data>) and
doSomething(List<Double>)
由于参数类型相同,Java 抱怨
有没有办法以某种方式使这种重载发生?
I was wondering if you can suggest something here.
I would like to have 2 methods:
doSomething(List<Data>) and
doSomething(List<Double>)
Since type of parameter is the same, Java is complaining
Is there a way to somehow make this overloading happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
遗憾的是,没有。因为 Java 通过擦除来实现泛型,所以这两个方法都将编译为:
由于不能有两个具有相同签名的方法,因此将无法编译。
你能做的最好的事情就是:
或者做同样令人讨厌的事情。
Sadly, no. Because Java implements generics via erasure those two methods would both compile down to:
Since you cannot have two methods with the same signature this will not compile.
The best you can do is:
or something equally nasty.
为什么不只是以不同的方式命名它们:
Why not just name them differently:
泛型仅在编译时可供编译器使用。它们不是执行时构造,因此上面的两个方法是相同的,因为在运行时两者也是等效的doSomething(List)。
Generics are only available to the compiler, at compile time. They are not an execution time construct, as such the two methods above are identical, as at runtime both are equivalent too doSomething(List).
由于类型擦除,这不起作用。您可以做的一件事是添加一个虚拟参数,如下所示:
丑陋,但它有效。
作为替代方案,您可以为这些方法指定不同的名称。
This doesn't work because of type erasure. One thing you could do is to add a dummy parameter, like so:
Ugly, but it works.
As an alternative, you could give the methods different names.