如何从 lambda 中编写这样的函数:
jButton.addActionListener(ae -> callAnyMethod());
因为我正在创建一个库并且想自己实现这样一个模式。 在 Java 8 和 lambda 发布之前,怎么会有人制作这样的模式?就像我试图接近的是:
我正在尝试在我的 CustomButton ActionListener 的 actionPerformed 方法中设置一个占位符并调用如下方法:
CustomButton.CustomButtonListener(placeholder method (); )
并且用户只需要创建一个方法并将其写入砖 block 中......例如名为 def() 的方法:
CustomButton.CustomButtonListener(def());
def 将自动传递到我的 CustomButtonListener 的 actionPerformed 方法,并在单击按钮时触发
编辑:
这就是我到目前为止想出的代码:
作为方法存储在我的 CustomButton 类中的 ActionListener:
public void CustomButtonListener(Object object){
addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// how to call the method stored in the Object "object" here? and actually run it?
}
});
以及按钮中的代码片段:
CustomButton button = new CustomButton();
button.CustomButtonListener(def());
public void def(){
String a = "lambda!";
System.out.print("a");
}
最佳答案
如果我没有误解你的问题,你的语法已经是正确的。
public static void main() {
...
jButton.addActionListener(e -> myListener());
...
}
...
public void myListener(){
dosomething();
}
这是这个的简写:
public static void main() {
...
MyListener myListener = new MyListener();
jButton.addActionListener(myListener);
...
}
public class MyListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
dosomething();
}
}
更多信息可以引用this .
更详细的解释也可以引用this ,在 Lambda 类型推断 部分下。
关于java - 如何在 ActionListener 中创建类似 lambda 的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44790907/