如何使用varargs方法的附加参数调用varargs方法 [英] How to call a varargs method with an additional argument from a varargs method

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

问题描述

我有一些varargs系统函数,其中T是一些实际类型,如 String

  sys(T ... args)

我想创建自己的功能,代表系统功能。我的功能也是一个varargs函数。我想通过函数的所有参数传递给系统函数,再加上附加的尾随参数。这样的东西:

  myfunc(T ... args){
T myobj = new T();
sys(args,myobj); //< - 当然这里错误。
}

如何更改错误行?
现在我只看到一种方法:使用维[args] + 1创建数组,并将所有项复制到新数组。
但也许存在一个更简单的方法?

解决方案


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


不是简单的方法。您需要创建一个新数组,并将 myobj 作为数组的最后一个元素。

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

如果您恰巧依靠Apache Commons Lang,您可以执行

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

或Guava

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


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.
}

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?

解决方案

Now I see only one way: create array with dimension [args] + 1 and copy all items to new array.

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);

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

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

or Guava

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆