拿这段简单的代码
new Thread(() -> {
}).start();
我知道它有效,但我如何编写自己的类以允许其他人以相同的方式使用它?
最佳答案
Lambda 致力于 Functional Interfaces ,因此,如果您的类或方法能够将此类接口(interface)作为参数,那么您可以以这种方式使用您的类/方法。
new Thread(() -> {
}).start();
这段代码的工作原理是 Thread
有一个重载的构造函数,它以函数接口(interface) Runnable
作为参数。
示例:如何编写自己的类
DoWork
是我们的功能接口(interface),它只有抽象方法 doit
public interface DoWork {
public void doit(String str);
}
让我们有一个名为 MyClass
的类,其构造函数将 DoWork
作为参数,并有一个方法 startWork
来开始工作(普通方法) .
public class MyClass {
DoWork dw;
public MyClass(DoWork dw) {
this.dw = dw;
}
public void startWork(String s){
dw.doit(s);
}
}
就是这样,我们可以在Main
class Main {
public static void main(String[] args) {
new MyClass(str -> System.out.println(str)).startWork("Hello print it!!!");
}
}
我们还可以使用带功能接口(interface)的方法参数的 lambda。
class Main {
public static void main(String[] args) {
test(str ->System.out.println(str), "Hello world!!!");
}
public static void test(DoWork d, String str) {
d.doit(str);
}
}
有关 Lambda 的更多信息,请参阅 http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
关于java - 这个 lambda 在下面发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33026448/