简体   繁体   English

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

[英]How to call a varargs method with an additional argument from a varargs method

I have some varargs system function, where T is some actual type, like String : 我有一些varargs系统函数,其中T是一些实际类型,如String

sys(T... args)

I want to create own function, which delegates to the system function. 我想创建自己的函数,它委托给系统函数。 My function is also a varargs function. 我的功能也是一个varargs功能。 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.
}

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. 现在我只看到一种方法:创建维度[args] + 1的数组,并将所有项目复制到新数组。 But maybe there exists a more simple way? 但也许存在一种更简单的方法?

Now I see only one way: create array with dimension [args] + 1 and copy all items to new array. 现在我只看到一种方法:创建维度[args] + 1的数组并将所有项目复制到新数组。

There is no simpler way. 没有更简单的方法。 You need to create a new array and include myobj as last element of the array. 您需要创建一个新数组并将myobj包含为数组的最后一个元素。

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

If you happen to depend on Apache Commons Lang you can do 如果您碰巧依赖Apache Commons Lang,您可以这样做

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

or Guava 或番石榴

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

You may call sys() twice if the order doesn't care: 如果订单不关心,您可以调用两次sys()

T myobj=new T();
sys(myobj);
sys(args);

If you can't use this, switch to collections (eg. LinkedList) for all of your functions. 如果您不能使用它,请切换到所有功能的集合(例如LinkedList)。

如果你可以使用番石榴 ,那么你可以这样做:

sys(ObjectArrays.concat(myobj, args))

Java 8解决方案:

sys(Stream.concat(Arrays.stream(args), Stream.of(myobj)).toArray(T[]::new));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM