How to call a varargs method with an additional argument from a varargs method(如何使用可变参数方法中的附加参数调用可变参数方法)

本文介绍了如何使用可变参数方法中的附加参数调用可变参数方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些可变参数系统函数,其中 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));

这篇关于如何使用可变参数方法中的附加参数调用可变参数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!