Reputation: 711
For example, here are two java methods
void test(int... values){}
And
void test(Object... values){}
If I make a call with arguments (1,2,3)
, there will be a compile error.
Also, I just need the facilities of java varargs, and can not declare my methods with argments int[] or Object[].
Is it possible?
Upvotes: 0
Views: 66
Reputation: 43391
You can always create the array explicitly:
foo.test(new int[] { 1, 2, 3 });
This works precisely as the vararg method would, so the bytecode won't even know the difference, and it'll resolve to the int...
overload.
The above is essentially equivalent to creating a variable for the int[]
, and passing that in:
int[] ints = { 1, 2, 3 };
foo.test(ints);
There isn't any other way to tell the compiler which overload you want.
Upvotes: 2
Reputation: 26185
If you explicitly convert and cast to make the actual arguments exactly match one of the formal argument lists, there is no ambiguity:
public class Test {
public static void main(String[] args) {
test(new int[] { 1, 2, 3 });
test((Object[]) new Integer[] { 1, 2, 3 });
}
public static void test(int... values) {
System.out.println("int version called");
}
public static void test(Object... values) {
System.out.println("Object version called");
}
}
Upvotes: 0