开发者

Calling ambiguously overloaded constructor in 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) {...}
}

the call

new A<Integer>(43);

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


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);


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜