【发布时间】:2015-11-11 14:10:54
【问题描述】:
我想创建一个类来存储方法引用列表,然后使用 Java 8 Lambda 执行所有方法引用,但我遇到了一些问题。
这是课
public class MethodExecutor {
//Here I want to store the method references
List<Function> listOfMethodsToExecute = new LinkedList<>();
//Add a new function to the list
public void addFunction(Function f){
if(f!=null){
listOfMethodsToExecute.add(f);
}
}
//Executes all the methods previously stored on the list
public void executeAll(){
listOfMethodsToExecute.stream().forEach((Function function) -> {
function.apply(null);
}
}
}
这是我为测试创建的类
public class Test{
public static void main(String[] args){
MethodExecutor me = new MethodExecutor();
me.addFunction(this::aMethod);
me.executeAll();
}
public void aMethod(){
System.out.println("Method executed!");
}
}
但是当我使用me.addFunction 传递this::aMethod 时出现问题。
怎么了?
【问题讨论】:
-
But there is something wrong when I pass this::aMethod- 这是因为某处有错误。如果您想要更具体的答案 - 请提出更具体的问题。 -
发布您遇到的具体错误和更具体的问题
-
A
Function接受一个参数并有一个返回值。aMethod两者都没有。 -
我该如何管理没有参数也没有返回值的方法?
-
如果在某些时候你想使用
Function(在java.util.function包中定义)确保提供类型参数,如Function<String,Integer>(或其他)。这里的示例使用Function原始类型,这将有效地禁用类型推断。
标签: java methods lambda java-8 parameter-passing