compiler construction - Why does autoboxing make some calls ambiguous in Java? -


I noticed today that auto-boxing can sometimes cause ambiguity in the method overload resolution. The simplest example seems like:

  test of public class {static zero F (object A, boolean B) {} static void f (object A, object B) {} static void m (Int a, Boolean B) {F (A, B); }}  

Once compiled, it causes the following error:

  test.java :: f reference is obscure, both methods f ( Java.Lang.Object, boolean) Test match method in stability and method f (java.lang.Object, java.lang.Object) (int a, boolean b) {f (a, b); } ^  

Fix this error is trivial: Use only clear auto-boxing:

  Fixed zero meters (int a, boolean b) {F ((Object) A, B); }  

who correctly calls the expected first charge.

Why did the overload resolution fail? Why did not the compiler auto-box get the first argument, and normally accept the second argument? Why do I have to explicitly request boxing?

When you first argue for objecting yourself, compiler autoboxing (JLS 3 15.12.2 ):

The first stage (§15.12.2.2) makes the overload resolution without the permission of the boxing or unblocking conversion, or the use of variables in the orientation of the orientation method if this If there is no duly method during the phase, the processing is continuing in the second phase.

If you do not explicitly insert it, then it will move to the second step of trying to match, allowing the method autoboxing, and then it is really unclear because your The second argument can be matched with a boolean or object.

The second step (§15.12.2.3) imposes a surcharge resolution on allowing boxing and unboxing, but still prevents the use of invocation of variable orientation method.

Why, in the second step, the compiler does not choose the second method because no autoboxing of Boolean logic is necessary? Because after two matching methods, only subtype conversion is used to determine the most typical method of two, regardless of any boxing or unboxing being replaced in the first place (§15.12.2.5) to match.

Apart from this: the compiler can not always choose the most specific method based on the need for automatic (joint) boxing, it can still be the result in vague cases, for example, it is still unclear :

public class test (A, B); } // Obscure}

Remember that the algorithm is defined and selected in JLS to choose the matching method (compile-time phase 2). There is no selective autoboxing or unboxing in step 2 once. The compiler chooses those methods (both methods in these cases) and applicable (again two modes) all , and then only after seeing boxing / unboxing, one chooses the most specific, which is unclear here .


Comments