Calling ambiguously overloaded constructor in Java

五迷三道 提交于 2019-12-11 03:04:19

问题


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

the call

new A<Integer>(43);

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


回答1:


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.

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.


More sophistries:

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.

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?

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?

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.




回答2:


You can drop the generics during construction (and suppress a warning):

A<Integer> a = new A(42);

or, less preferably use reflection (where again you'd have to suppress warnings)

Constructor<A> c = A.class.getDeclaredConstructor(Integer.class);
A<Integer> a = c.newInstance(42);



回答3:


Indeed, it is ambiguous, and so doesn't compile if you try new A<Integer>(new Integer(0)).



来源:https://stackoverflow.com/questions/5692466/calling-ambiguously-overloaded-constructor-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!