简体   繁体   中英

Why does Java think my constructor call is ambiguous?

I have the following code in a java application:

UserMessage um = new UserMessage("a string", 
                                 false, 
                                 "another String", 
                                 "one last string");

Eclipse is telling me there's an error with this line of code with:

The constructor UserMessage(String, Object[]) is ambiguous  

The signatures for all of the constructors for UserMessage are:

1. public UserMessage(String key)
2. public UserMessage(String key, boolean escapeHTML, Object... args)
3. public UserMessage(String key, Object... args)
4. public UserMessage(ErrorCode code)
5. public UserMessage(ErrorCode code, Object... args)

To me it seems obvious that the constructor I'm calling should point to #2 above. The error seems to suggest to me that it thinks that it can potentially point to the third constructor.

Why is there any ambiguity to this call? The only thing I can think of is if false is, for some reason cast to a Boolean object, but clearly that's not what my code does - so this would have to be something the java compiler does on its own.

It looks like an issue with autoboxing the boolean value into a Boolean, so the compiler can't tell whether the constructor is being passed a String, a boolean, and two Strings in a varargs Object array (#2), or a String and a varargs Object array containing a Boolean, a String, and another String (#3).

"There is a strong synergy between autoboxing and varargs,"

ETA: If you would like to differentiate the constructors, you might try changing the Object...varargs to String... varargs , if that's possible in your implementation. That should prevent the autoboxing of the boolean into a Boolean creating ambiguity between constructors #2 and #3.

ETA2: Just checked my suggestion in Eclipse, and changing the Object... varargs in your constructors to String... varargs eliminates the ambiguity error, so it looks like the issue is autoboxing of the boolean into a Boolean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM