Invoking an ambiguously overloaded constructor in Java

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

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

call

new A<Integer>(43);

is ambiguous, and I see no way to solve it. Whether there is a?

+2
source share
3 answers

Yes, members of the parameterized type JLS3 # 4.5.2 may find themselves in conflicts that are prohibited in the declaration of the normal class (# 8.4.8). It is very easy to come up with many examples of this kind.

And in Java, none of the constructors in your example is more specific than the other, because there is no subtyping relationship between Tand Integer. see also Link ambiguous with generics

​​, . .


:

<T extends Integer>, T Integer, , 1-, .

javac . Java , javac . . Erasure Java: ?

: <T extends Integer>, Integer - final, T Integer, Integer T, , ?

. final . final Integer , Java , final .

+2

( ):

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

, , ( )

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

, , new A<Integer>(new Integer(0)).

+2

All Articles