I would like to know if it is possible to unpack an Object array into separate Object on method call which accepts vargs. This question is similar to this one.
I have a code like:
public class Test {
public static Object doWork(Object... objects){
System.out.println(objects.length);
return objects;
}
public static void main(String[] args){
Object res = doWork("one", "two");
res = doWork("three", res);
}
}
I would like to unpack the res
object in the second call so it would receive an object array with length 3 instead of length 2 as now (where the second position is an Object array of length 2, having then all three arguments).
Is even that possible in Java?
More detailed:
By doing
Object res = doWork("one", "two");
res = doWork("three", res);
the second call gets called as:
doWork( Object[ "three", Object[ "one", "two" ] ] )
where i would like:
doWork(Object[ "one", "two", "three" ] )
I know this can be achieved by doing:
public static void main(String[] args){
res = doWork("one", "two");
List<Object> los = Arrays.asList(res);
los = new ArrayList<>(los); // Can't modify an underlying array
los.add("three");
res = doWork(los.toArray());
}
But I'm looking for something like the unpack
Lua built in function or the Python way described in the previously mentioned SO question.
Both answers given by @chancea and @Cyrille-ka are good and also solve the problem. One of the facts that might be a good idea to take into account is if the signature of the method can be modified. @cyrille-ka answer respects the function's signature, whereas @chancea does not. However I think in most cases one can just write asimple wrapper function to another one, so that shouldn't be a problem. On the other hand @chancea's way might be easier to use while programing (there no possible mistake of forgetting to call the unpack function).