简体   繁体   English

Java为什么认为我的构造函数调用不明确?

[英]Why does Java think my constructor call is ambiguous?

I have the following code in a java application: 我在Java应用程序中有以下代码:

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: Eclipse告诉我这行代码存在错误:

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

The signatures for all of the constructors for UserMessage are: UserMessage的所有构造函数的签名为:

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. 在我看来,我正在调用的构造函数似乎应该指向上面的#2。 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. 我唯一能想到的是如果由于某种原因将false强制转换为Boolean对象,但是很明显,这不是我的代码所要做的-因此,这必须是Java编译器自行执行的操作。

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). 将布尔值自动装箱成布尔值似乎是一个问题,因此编译器无法确定是否在varargs Object数组(#2)中将构造函数传递给String,布尔值和两个String,或者传递给String和包含布尔值,字符串和另一个字符串(#3)的varargs对象数组。

"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. ETA:如果您想区分构造函数,则可以尝试将Object ... varargs更改为String ... varargs,如果可以在实现中实现的话。 That should prevent the autoboxing of the boolean into a Boolean creating ambiguity between constructors #2 and #3. 这应该防止将布尔值自动装箱为布尔值,从而在构造函数#2和#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. ETA2:刚刚检查了我在Eclipse中的建议,并将构造函数中的Object ... varargs更改为String ... varargs消除了歧义错误,因此问题似乎是将布尔值自动装箱成布尔值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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