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));
这篇关于如何使用可变参数方法中的附加参数调用可变参数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用可变参数方法中的附加参数调用可变参数方法


基础教程推荐
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01