๐งช Unit Test 005: Overloading Arguments Resolution โ
๐ Preface โ
Java allows method overloading and supports varargs, basically methods that accept a variable number of arguments. When both a general varargs method and a more specific overload exist, the compiler follows a strict resolution hierarchy. This test demonstrates how Java resolves method calls when both match, but one is more specific than the other.
๐ฌ Test Case โ
public class T_005_OverloadingResolution {
public static class TestClass {
public static int method(Object... args) {
return 0;
}
public static int method(String arg, Object... args) {
return 1;
}
}
@Test
public void test() {
Assertions.assertSame(1, TestClass.method("test"));
Assertions.assertSame(0, TestClass.method((Object) "test"));
}
}๐ Why This Matters โ
Java resolves overloaded methods by most specific match. In the first case, the method with the String parameter is more specific than Object..., so it is chosen. In the second case, no String overload matches, so the general varargs method is selected. Misunderstanding this behaviour can lead to the wrong overload being called, a common trap when working with APIs that use varargs heavily, though IDEs normally helps out the developer by highlighting the method being called.