Java 7用varargs重载 [英] Java 7 overloading with varargs

查看:78
本文介绍了Java 7用varargs重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
带有varargs和重载的bug?

Possible Duplicate:
bug with varargs and overloading?

任何人都可以向我解释一下这是如何工作的:

could anyone explain me how this one works:

class Vararg {
    static void vararg(int... x) {
        System.out.println("Integer..."); 
    }

    static void vararg(long... x) { 
        System.out.println("long..."); 
    }

    public static void main(String [] args) {
        int s = 0;
        vararg(s,s);
    }
}

获取编译时错误

class Vararg {
    static void vararg(Integer... x) {
        System.out.println("Integer..."); 
    }

    static void vararg(long... x) {
        System.out.println("long..."); 
    }

    public static void main(String [] args) {
        int s = 0;
        vararg(s,s);
    }
}

也得到编译时错误.将重载与varargs一起使用时的机制是什么?重载varargs方法是否是一个错误?

Also get compile time error. What is the mechanism when we use overloading with varargs? Is it a bug with overloading varargs methods?

推荐答案

实质上,要确定哪种方法适用,请

In substance, to determine which method is applicable, the compiler runs a few steps:

  • 首先尝试找到一种不使用装箱/拆箱或可变参数的方法
  • 第二次尝试找到一种方法,允许装箱/拆箱,但没有可变参数
  • 第三次允许装箱,拆箱和可变参数

对于您而言,第三步适用于所有方法.

In your case, the third step is applicable to all methods.

然后,编译器确定哪些方法适用,以及一个方法是否比另一个方法更具体.详细规则在 JLS中15.12.2.4 .简而言之,它检查类型并检查一种类型是否比另一种类型更具体(即,对于引用,一种类型是另一种的子类,或者对于基元,一种类型比另一种类型窄).

The compiler then determines which methods are applicable and if one is more specific than another. The detailed rules are in the JLS 15.12.2.4. In short, it looks at the types and checks if one is more specific than another (i.e. one type is a subclass of the other for references or one type is narrower than another for primitives).

在您的情况下:

  • 在示例1中,两种方法都适用,但是intlong更具体,因此选择了vararg(int...)
  • 在示例2中,Integerlong没有 specificity 关系(一个是引用,另一个是primitve),因此两者都具有最大的特定性,并且存在导致编译错误.
  • in example 1, both methods are applicable but int is more specific than long so the vararg(int...) is chosen
  • in example 2, Integer has no specificity relationship with long (one is a reference the other is a primitve), so both are maximally specific and there is an ambiguity which leads to a compile error.

编辑

我以为您是在说您的第一个示例可以编译,但第二个示例不能编译(这是预期的行为).您似乎在说都不编译,在这种情况下,这可能是由于您的javac版本中的一个错误所致,该错误已由Java 7修复. oracle.com/technetwork/java/javase/compatibility-417013.html"rel =" noreferrer>发行说明,称为最特定的变量参数选择中的更改"部分.

I thought you were saying that your first example compiles but not the second (which is the expected behaviour). You seem to be saying that neither compiles, in which case it is probably due to a bug in you version of javac, which has been fixed with Java 7. See details in the release notes, section called "Changes in Most Specific Varargs Method Selection".

这篇关于Java 7用varargs重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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