I'm trying to write the prototype of a Java function that can be called with any number of integers and strings:
myMethod(1, 2, 3, "Hello", "World"); // Valid call
myMethod(4, "foo", "bar", "foobar"); // Valid call
Ideally, I would like the ints and strings to be given in any order (and possibly mixed):
myMethod(1, "Hello", 2, "World", 3); // Valid call
I thought of using varargs, but there can be only one in the prototype. Another idea I've had is to use the following prototype:
public void myMethod(Object ... objs) { [...] }
...but I feel that there should be a compilation error in case it is called with something other than the expected types. Of course, a runtime check (instanceof
) could be performed, but that wouldn't be a very elegant solution, would it?
How would you do it?
There is no way in the Java programming language to get it to work so that you can pass an arbitrary number of strings and integers, and have the compiler give an error when you pass something else than a string or integer.