如何使用可变参数方法中的附加参数调用可变参数方法

2022-01-18 00:00:00 delegates java variadic-functions

我有一些可变参数系统函数,其中 T 是一些实际类型,例如 String:

I have some varargs system function, where T is some actual type, like String:

sys(T... args)

我想创建自己的函数,委托给系统函数.我的函数也是一个可变参数函数.我想将我的函数的所有参数传递给系统函数,加上一个额外的尾随参数.像这样的:

I want to create own function, which delegates to the system function. My function is also a varargs function. I want to pass through all the arguments for my function through to the system function, plus an additional trailing argument. Something like this:

myfunc(T... args) {
    T myobj = new T();
    sys(args, myobj); // <- of course, here error.
}

我需要如何更改出现错误的行?现在我只看到一种方法:创建维度为 [args] + 1 的数组并将所有项目复制到新数组中.但也许还有更简单的方法?

How do I need to change the line with the error? Now I see only one way: create array with dimension [args] + 1 and copy all items to the new array. But maybe there exists a more simple way?

推荐答案

现在我只看到一种方法:创建维度为 [args] + 1 的数组并将所有项目复制到新数组中.

没有更简单的方法.您需要创建一个新数组并将 myobj 作为数组的最后一个元素.

There is no simpler way. You need to create a new array and include myobj as last element of the array.

String[] args2 = Arrays.copyOf(args, args.length + 1);
args2[args2.length-1] = myobj;
sys(args2);

如果你碰巧依赖于 Apache Commons Lang,你可以这样做

If you happen to depend on Apache Commons Lang you can do

sys(ArrayUtils.add(args, myobj));

或番石榴

sys(ObjectArrays.concat(args, myobj));

相关文章