Ambiguous compilation error with Maven and apache utils

I am using org.apache.commons.lang3.BooleanUtils in commons-lang3 (version 3.1). When I try to compile the following line of code

 BooleanUtils.xor(true, true); 

using maven-compiler-plugin (version 3.3), I get a compilation error message:

 [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 

I am using Java 1.7.0_55 to compile.

How can i solve this?

+5
source share
2 answers

The problem arises because the method signature has variable arguments. When a method is called, there are three phases during which a search is made for all applicable methods. Methods with variable arguments are executed in phase 3 , where boxing and unpacking are also allowed.

So both xor(boolean...) and xor(boolean...) applicable here because boxing is taken into account. When multiple methods are applied, only the most specific is called. But in this case, boolean and boolean cannot be compared, therefore there is no more specific method, therefore a compiler error: both methods correspond.

The workaround is to create an explicit array:

 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; } 
+4
source

Funny: the corner case when autoboxing is right on your way.

The easiest way to fix this is to write

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

Source: https://habr.com/ru/post/1236815/


All Articles