Maven 和 apache utils 的编译错误不明确

Ambiguous compilation error with Maven and apache utils

我在 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

我用Java1.7.0_55编译.

我该如何解决这个问题?

有趣:自动装箱直接挡住你的路的角落案例。

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

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

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

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

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

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;
}