In Java, I am trying to use a method from a library which accepts varargs of Object type:
static Result process(Object head, Object... tail)
In my code, the number of arguments is known at run time, so I tried to use an array to collect all arguments and pass them to process(..)
:
T[] items = ...;
Result r = process(items);
However, as Array itself is an Object, the call does not unwrap array items and the whole array is considered as a single argument.
Any idea how multiple arguments can be boxed and passed to a method with varargs of Object type?
You have a non-variadic parameter head
.
This means that you require at least head
to be passed to the method, with optional variadic arguments after.
Therefore, you should call:
Object[] allArgs = new Object[]{object1, object2, object3};
Object[] varags = Arrays.copyOfRange(allArgs, 1, allArgs.length);
process(allArgs[0], varags)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.