When passing null as argument to overloaded varargs method(Object... o) and non-varargs method(Object o), why varargs method is executed?

Dongmin Sun :

For example, a class include two methods,

public void find(Object id);
public void find(Object... ids);

When I invoking find(null), why jvm actually execute the last one?

In accepted answer of Calling Java varargs method with single null argument? we can read that

Java doesn't know what type it is supposed to be. It could be a null Object, or it could be a null Object array. For a single argument it assumes the latter."

but that still doesn't explain it. Can anyone provide some more information like from language specification?

apangin :

Object[] is more specific type than Object.

According to JLS §15.12.2

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

The same chapter also has an example exactly about the situation in question.

[...] a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=70664&siteId=1