在 Java 7 中使用方法重载时,为什么自动装箱不推翻可变参数?

我们的 Java 项目中有一个 LogManager 类,如下所示:

We have a class LogManager in our Java project which looks like this:

public class LogManager {

    public void log(Level logLevel, Object... args) {
        // do something
    }

    public void log(Level logLevel, int value, Object... args) {
        // do something else
    }
}

在Debianeveryting下使用OpenJDK 6编译项目时工作正常.当使用 OpenJDK 7 构建(使用 ant 完成)产生以下错误并且构建失败:

When compiling the project with OpenJDK 6 under Debian everyting works fine. When using OpenJDK 7 the build (done with ant) produces the following errors and the build fails:

[javac] /…/LogManager.java:123: error: reference to log is ambiguous,
                      both method log(Level,Object...) in LogManager
                      and method log(Level,int,Object...) in LogManager match
[javac]       log(logLevel, 1, logMessage);
[javac]       ^
[javac] /…/SomeOtherClass.java:123: error: reference to log is ambiguous,
                      both method log(Level,Object...) in LogManager
                      and method log(Level,int,Object...) in LogManager match
[javac]       logger.log(logLevel, 1, logMessage);
[javac]             ^

只要 1 没有自动装箱,方法调用应该是明确,因为 1 是一个 int 并且不能向上转换为 Object.所以为什么自动装箱不会在这里推翻可变参数吗?

As long as the 1 is not autoboxed, the method call should be unambiguous as 1 is an int and cannot be upcast to Object. So why doesn't autoboxing overrule varargs here?

Eclipse(使用来自 eclipse.org 的 tar.gz 安装)编译它没有无论是否安装了 OpenJDK 6.

Eclipse (installed using the tar.gz from eclipse.org) compiles it no matter if OpenJDK 6 is installed or not.

非常感谢您的帮助!

编译器在这两种情况下都会获得选项 source="1.6"target="1.6".Eclipse 编译说明仅作为注释.

The compiler gets the option source="1.6" and target="1.6" in both cases. The Eclipse compiling note is just meant as a comment.

推荐答案

估计和bug有关 #6886431,这似乎在 OpenJDK 7 中也已修复.

I guess it's related to bug #6886431, which seems to be fixed in OpenJDK 7 as well.

问题在于 JLS 15.12.2.5选择最具体的方法表示当前者的形式参数类型是后者的形式参数的子类型时,一种方法比另一种方法更具体.

The problem is that JLS 15.12.2.5 Choosing the Most Specific Method says that one method is more specific than another one when types of formal parameters of the former are subtypes of formal parameters of the latter.

由于 int 不是 Object 的子类型,因此您的方法都不是最具体的,因此您的调用不明确.

Since int is not a subtype of Object, neither of your methods is the most specific, thus your invocation is ambiguous.

但是,以下解决方法是可能的,因为 IntegerObject 的子类型:

However, the following workaround is possible, because Integer is a subtype of Object:

public void log(Level logLevel, Object... args) { ... }
public void log(Level logLevel, Integer value, Object... args) { ... } 

相关文章