使用方法引用 [英] Using method references
问题描述
我有一个名为 saveButton
的 JButton
,并希望它调用保存
单击时的方法。当然我们可以使用旧方法来做到这一点:
I've got a JButton
called saveButton
and want it to call the save
method when it is clicked. Of course we can do it using the old approach:
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
save();
}
});
但今天我想使用方法引用等新的Java 8功能。为什么
But today I want to use new Java 8 features like method references. Why does
saveButton.addActionListener(this::save);
不起作用?如何使用方法引用完成?
not work? How is it done using method references?
推荐答案
方法 actionPerformed(ActionEvent e)
需要单个参数 e
。如果要使用方法引用,则方法必须具有相同的签名。
Method actionPerformed(ActionEvent e)
requires single parameter e
. If you want to use a method reference, your method must have the same signature.
private void myActionPerformed(ActionEvent e) {
save();
}
然后你可以使用方法参考:
Then you can use method reference:
saveButton.addActionListener(this::myActionPerformed);
或者你可以改用lambda(注意 e
参数):
Or you can use lambda instead (notice e
parameter):
saveButton.addActionListener(e -> save());
这篇关于使用方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!