这个问题出现在我的工作编程过程中;它与当前的任务无关,但我仍然很好奇是否有人有答案。
在 Java 1.5 及更高版本中,您可以使用可变数量的参数来使用方法签名,并使用省略号语法:
public void run(Foo... foos) {
if (foos != null) {
for (Foo foo: foos) { //converted from array notation using autoboxing
foo.bar();
}
}
}
假设我想对 foos 列表中的每个 foo 执行一些操作,然后将此调用委托给我的对象上的某个字段,并保留相同的 API。我该怎么做?我想要的是这样的:
public void run(Foo... foos) {
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public void run(MyFoo... myFoos) {
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) { //converted from array notation using autoboxing
myFoo.bar();
}
}
}
这不编译。我怎样才能做到这一点(将可变数量的 MyFoo 传递给 run(MyFoo...) 方法)?