Why doesn't autoboxing overrule varargs when using method overloading in Java 7?

我怕爱的太早我们不能终老 提交于 2019-11-27 08:38:37

I guess it's related to bug #6886431, which seems to be fixed in OpenJDK 7 as well.

The problem is that JLS 15.12.2.5 Choosing the Most Specific Method says that one method is more specific than another one when types of formal parameters of the former are subtypes of formal parameters of the latter.

Since int is not a subtype of Object, neither of your methods is the most specific, thus your invocation is ambiguous.

However, the following workaround is possible, because Integer is a subtype of Object:

public void log(Level logLevel, Object... args) { ... }
public void log(Level logLevel, Integer value, Object... args) { ... } 

Eclipse uses it's own compiler, so what Eclipse does eventually follows what the SUN / Oracle provided compilers does; however, sometimes (like in this case) there are differences.

This could "go either way" and probably in Java 6, the issue wasn't addressed in detail. Since Java has a strong requirement to reduce the number of "ambiguous" meanings in its environment (to enforce same behavior across many platforms), I'd imagine that they tightened up (or directly specified) the decided behavior in the 7 release.

You just got caught on the "wrong" side of new specification clarification. Sorry, but I think you'll be writing a bit of this

public void log(Level logLevel, Object... args) {
    if (args != null && args[0] instanceof Integer) {
      // do something else
    } else {
      // do something
    }
}

into your new solution.

This is skating way closer to the edge than is prudent. Unless you can find clear language in the spec as to behavior, I'd avoid anything ambiguous like this.

Even if it is in the spec, readers of your code won't have done the language lawyering to know, so you'll need to comment it to explain, and they may or may not read the comment. They may not even consider one of the alternatives - just see one overload that fits, and run with that. An accident waiting to happen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!