【发布时间】:2017-12-01 03:13:54
【问题描述】:
我如何从 lambda 编写类似这样的函数:
jButton.addActionListener(ae -> callAnyMethod());
因为我正在创建一个库并且想自己实现这样的模式。 在 Java 8 和 lambda 发布之前,有人会如何制作这样的模式?就像我试图接近的是:
我正在尝试在我的 CustomButton ActionListener 的 actionPerformed 方法中设置一个占位符并调用如下方法:
CustomButton.CustomButtonListener(placeholder method (); )
而用户只需要创建一个方法并将其写入砖块中......例如名为 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?
}
});
以及按钮中的代码 sn-p:
CustomButton button = new CustomButton();
button.CustomButtonListener(def());
public void def(){
String a = "lambda!";
System.out.print("a");
}
【问题讨论】:
-
通过使用 Java 中现有的 lambda 功能?我不认为我理解你的问题。您能否发布到目前为止您拥有的代码以及运行它时会发生什么以及您预期会发生什么?
-
你是在暗示代码不是纯Java吗?为什么不呢?
-
Lambda expressions在Java 8中引入,如果可以使用版本>7,则可以使用它们。 -
@SmartCodeNoBugs 为什么不直接看一下 ActionListener、ActionEvent 和 JButton 的文档和源代码?并阅读有关 lambdas 的文档? docs.oracle.com/javase/tutorial/java/javaOO/…
-
JButton、ActionListener 和 ActionEvent 存在,就像它们在 Java 8 中一样,从 Java 2 开始。没有任何改变。 Lambda 只是一种创建接口实例的新方法。