在Java中调用ambiguously重载的构造函数 [英] Calling ambiguously overloaded constructor in Java

查看:251
本文介绍了在Java中调用ambiguously重载的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚看到这个C#问题,想知道,如果类似的东西可能发生在Java。它可以

I just saw this C# question and wondered, if something similar could happen in Java. It can, with

class A<T> {
    A(Integer o) {...}
    A(T o) {...}
}

调用

new A<Integer>(43);

是不明确的,我看不到如何解决它。有没有?

is ambiguous and I see no way how to resolve it. Is there any?

推荐答案

是的,参数化类型的成员 JLS3#4.5.2 可能会出现在正常类声明中排除的冲突中(#8.4 .8)。这是很容易想出这样的很多例子。

Yes, members of a parameterized type JLS3#4.5.2 can end up in conflicts that are precluded in a normal class declaration(#8.4.8). It's pretty easy to come up with many examples of this kind.

在Java中,你的示例中的构造函数都不是比其他更具体,因为没有子类型关系 T Integer 之间。另请参见引用与泛型模糊不清

And in Java, neither constructor in your example is more specific than the other, because there is no subtyping relation between T and Integer. see also Reference is ambiguous with generics

如果方法重载产生了这种歧义,我们通常可以选择使用不同的方法名。但是构造函数不能重命名。

If method overloading creates this kind of ambiguity, we can usually choose to use distinct method names. But constructors cannot be renamed.

更多诡辩:

如果< T extends Integer> ,则实际上 T Integer 的子类型,那么第二个构造函数比第一个构造函数更具体,并且将选择第二个构造函数。

If <T extends Integer>, then indeed T is a subtype of Integer, then the 2nd constructor is more specific than the 1st one, and the 2nd one would be chosen.

实际上javac不允许这两个构造函数共存。当前Java语言规范中没有禁止它们,但是字节码中的限制迫使javac禁止它们。请参见在Java中键入擦除和重载:为什么这个工作?

Actually javac wouldn't allow these two constructors to co-exist. There is nothing in the current Java language specification that forbids them, but a limitation in the bytecode forces javac to forbid them. see Type Erasure and Overloading in Java: Why does this work?

另一点:如果< T extends Integer> code> Integer 是 final ,T只能是 Integer code> Integer 也必须是 T 的子类型,因此不是第二个构造函数也比第一个更具体?

Another point: If <T extends Integer>, since Integer is final, T can only be Integer, so Integer must also be a subtype of T, therefore isn't the 2nd constructor also more specific than the 1st?

否。 final 在子类型关系中不被考虑。实际上可以从 Integer 中删除​​ final 一天,Java甚至指定删除 final 不会破坏二进制兼容性。

No. final isn't considered in subtyping relations. It is actually possible to drop final from Integer one day, and Java even specifies that removing final does not break binary compatibility.

这篇关于在Java中调用ambiguously重载的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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