public Email myMethod(Function<MyObject, String>... functions) { ... }我创建了一个函数列表,并希望传递给myMethod:
List<Function<MyObject, String>> functions= new ArrayList<>();
if (condition1) {
functions.add(myObject->myObject.getStringX());
} else {
functions.add(myObject->myObject.getStringY());
}
myMethod(functions);//Does not compile, I must find a solution here
to convert my list of functions to an array that can be accepted as
myMethod argument发布于 2018-09-04 20:42:53
它是一个函数的array,所以创建一个这样的函数数组并传递它。
或者您可以使用以下命令调用它:
Function<MyObject, String>[] array = new Function[functions.size()];
functions.toArray(array);
myMethod(array);只需注意,您不能创建泛型数组,但可以声明一个泛型数组。
发布于 2018-09-04 20:59:41
我相信一个更干净的代码应该是
Function [] functionsArray = new Function[functions.size()];
for (int i=0;i< functions.size();i++) {
functionsArray[i] = functions.get(i);
}
myMethod(functionsArray); // unchecked assignment here ofcourse然后我的IDE建议我把它写成
myMethod(functions.toArray(new Function[0]));https://stackoverflow.com/questions/52166599
复制相似问题