【问题标题】:Ambiguous compilation error with Maven and apache utilsMaven 和 apache utils 的模棱两可的编译错误
【发布时间】:2016-02-28 09:05:24
【问题描述】:

我在commons-lang3(3.1 版)中使用org.apache.commons.lang3.BooleanUtils。 当我尝试编译下一行代码时

BooleanUtils.xor(true, true);

使用maven-compiler-plugin(3.3 版),我收到一条编译失败消息:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project exchange: Compilation failure
[ERROR] MyClass.java:[33,34] reference to xor is ambiguous, both method xor(boolean...) in org.apache.commons.lang3.BooleanUtils and method xor(java.lang.Boolean...) in org.apache.commons.lang3.BooleanUtils match

我使用Java 1.7.0_55编译。

我该如何解决这个问题?

【问题讨论】:

    标签: java apache maven apache-commons apache-commons-lang3


    【解决方案1】:

    有趣的是:自动装箱直接妨碍您的极端情况。

    解决这个问题的最简单方法是编写

    BooleanUtils.xor((boolean) true, (boolean) true)
    

    【讨论】:

    • 其实最简单的写法是false。
    • 其实这样并不能解决编译错误。它仍然存在,即使有明确的演员表
    • 我可以验证这会导致编译器错误。这是我来这里之前尝试的第一件事。 Java 编译器仍然无法判断数组的类型是布尔型还是布尔型。
    【解决方案2】:

    出现问题是因为方法的签名具有可变参数。调用方法时,有 3 个阶段搜索所有适用的方法。带有可变参数的方法在phase 3 中搜索,其中也允许装箱和拆箱。

    所以xor(boolean...) 和xor(Boolean...) 都适用于这里,因为考虑了拳击。当多种方法适用时,仅调用最具体的方法。但是在这种情况下,boolean 和Boolean 无法比较,因此没有更具体的方法,因此编译器错误:两种方法都匹配。

    一种解决方法是创建一个显式数组:

    public static void main(String[] args) {
        xor(new boolean[] { true, false }); // will call the primitive xor
        xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }); // will call the non-primitive xor
    }
    
    private static Boolean xor(Boolean... booleans) {
        System.out.println("Boolean...");
        return Boolean.TRUE;
    }
    
    private static boolean xor(boolean... booleans) {
        System.out.println("boolean...");
        return true;
    }
    

    【讨论】:

    • 这行得通,但对我来说看起来真的很糟糕的代码:) 我很惊讶这可能发生在 apcahe-commons-lengs3
    猜你喜欢
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多