如何在Java中将函数作为参数传递? [英] How to pass a function as a parameter in Java?
问题描述
在Java中,如何将一个函数作为另一个函数的参数传递?
In Java, how can one pass a function as an argument of another function?
推荐答案
Java 8 及更高版本
使用 Java 8+ lambda 表达式,如果您的类或接口只有一个抽象方法(有时称为 SAM 类型),例如:
public interface MyInterface {
String doSomething(int param1, String param2);
}
然后在使用 MyInterface 的任何地方,您都可以替换 lambda 表达式:
then anywhere where MyInterface is used, you can substitute a lambda expression:
class MyClass {
public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}
例如,您可以非常快速地创建一个新线程:
For example, you can create a new thread very quickly:
new Thread(() -> someMethod()).start();
并使用方法参考语法使其均匀清洁工:
And use the method reference syntax to make it even cleaner:
new Thread(this::someMethod).start();
如果没有 lambda 表达式,最后两个示例将如下所示:
Without lambda expressions, these last two examples would look like:
new Thread(new Runnable() { someMethod(); }).start();
Java 8 之前
一个常见的模式是将它包装"在一个接口中,例如Callable
,然后你传入一个Callable:
Before Java 8
A common pattern would be to 'wrap' it within an interface, like Callable
, for example, then you pass in a Callable:
public T myMethod(Callable<T> func) {
return func.call();
}
这种模式被称为命令模式.
请记住,最好为您的特定用途创建一个界面.如果您选择使用 callable,那么您可以将上面的 T 替换为您期望的任何类型的返回值,例如 String.
Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.
针对您在下面的评论,您可以说:
In response to your comment below you could say:
public int methodToPass() {
// do something
}
public void dansMethod(int i, Callable<Integer> myFunc) {
// do something
}
然后调用它,也许使用匿名内部类:
then call it, perhaps using an anonymous inner class:
dansMethod(100, new Callable<Integer>() {
public Integer call() {
return methodToPass();
}
});
请记住,这不是技巧".它只是 Java 中与函数指针等价的基本概念.
Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.
这篇关于如何在Java中将函数作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!