当重载编译器仅在 varargs 参数存在的情况下不喜欢原始对象时 [英] When overloading compiler does not prefer primitive to Object only in case of varargs parameter presence

查看:54
本文介绍了当重载编译器仅在 varargs 参数存在的情况下不喜欢原始对象时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请您帮我理解为什么编译第一次调用 testVargArgsAutoboxingPriority 会失败?

Please, could you help me to understand why compilation of first call of testVargArgsAutoboxingPriority fails?

在第二次调用的情况下,编译器可以通过首选原始(第一个参数)而不是对象来选择正确的方法,但是在添加可变参数参数之后,编译器无法再进行选择.

In case of second call compiler is able to select proper method by preferring primitive (first parameter) to Object but after varargs parameter addition compiler is not able to make the selection any more.

失败信息是

\jdk1.6.0_45\bin\javac.exe ocjp6/AutoBoxingOldStyleVarargsPriority.java
ocjp6\AutoBoxingOldStyleVarargsPriority.java:7: reference to testVargArgsAutoboxingPriority is ambiguous, both method testVargArgsAutoboxing
Priority(java.lang.Integer,boolean...) in ocjp6.AutoBoxingOldStyleVarargsPriority and method testVargArgsAutoboxingPriority(int,boolean...)
in ocjp6.AutoBoxingOldStyleVarargsPriority match
      testVargArgsAutoboxingPriority( 5, true ); // the line compilation fails
      ^
1 error

完整的代码清单是

package ocjp6;

public class AutoBoxingOldStyleVarargsPriority
{
   public static void main( final String[] args )
   {
      testVargArgsAutoboxingPriority( 5, true ); // the line compilation fails
      testVargArgsAutoboxingPriority( 5 );
   }

   private static void testVargArgsAutoboxingPriority( Integer b, boolean... c )
   {}
   private static void testVargArgsAutoboxingPriority( int b, boolean... c )
   {}

   private static void testVargArgsAutoboxingPriority( Integer b )
   {}
   private static void testVargArgsAutoboxingPriority( int b )
   {}
}

推荐答案

答案在于 JLS - 15.12.2.编译时步骤 2:确定方法签名 和上面的@TheNewIdiot 答案.这里有更详细的解释:

The answer lies in the JLS - 15.12.2. Compile-Time Step 2: Determine Method Signature and on @TheNewIdiot answer above. Here is a more detailed explanation:

对于方法:

private static void testVargArgsAutoboxingPriority( Integer b ) {}
private static void testVargArgsAutoboxingPriority( int b ) {}

编译器只需要第一阶段就知道调用哪个方法.在第一阶段,它不会混合盒装类型和原始类型.

The compiler needs only the first phase in order to know which method to call. And in the first phase it's not mixing boxed and primitive types.

但是方法:

private static void testVargArgsAutoboxingPriority( Integer b, boolean... c ) {}
private static void testVargArgsAutoboxingPriority( int b, boolean... c ) {}

包含 varargs 参数,编译器需要进入第三阶段尝试区分它们.但是到了第三阶段就不能再区分盒装类型和它对应的原始类型了.

contains varargs arguments and the compiler needs to get to the third phase trying to distinguish between them. But in the third phase is not able anymore to make the distinction between a boxed type and its corresponding primitive type.

这篇关于当重载编译器仅在 varargs 参数存在的情况下不喜欢原始对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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