使用方法引用
我有一个名为saveButton
的JButton
并希望它在单击时调用save
方法。 当然,我们可以使用旧方法来做到这一点:
saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } });
但今天我想使用新的Java 8function,如方法引用。 为什么
saveButton.addActionListener(this::save);
不行? 如何使用方法引用完成?
方法actionPerformed(ActionEvent e)
需要单个参数e
。 如果要使用方法引用,则方法必须具有相同的签名。
private void myActionPerformed(ActionEvent e) { save(); }
然后你可以使用方法参考:
saveButton.addActionListener(this::myActionPerformed);
或者你可以改用lambda(注意e
参数):
saveButton.addActionListener(e -> save());
你可以使用lambda:
saveButton.addActionListener((ActionEvent e) -> save());
这可以完成,因为ActionListener是一个function接口(即只有一个方法)。 function接口是仅包含一个抽象方法的任何接口。 Lambdas是电话的简写。
作为使用Lambda的替代方法,您可以通过让您的类实现相关接口(或其他具有实例变量的类)来使用方法引用。 这是一个完整的例子:
public class Scratch implements ActionListener { static JButton saveButton = new JButton(); public void save(){}; public void contrivedExampleMethod() { saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } }); // This works regarless of whether or not this class // implements ActionListener, LAMBDA VERSION saveButton.addActionListener((ActionEvent e) -> save()); // For this to work we must ensure they match // hence this can be done, METHOD REFERENCE VERSION saveButton.addActionListener(this::actionPerformed); } @Override public void actionPerformed(ActionEvent e) { save(); } }
这当然只是一个人为的例子,但它可以通过任何方式完成,假设您传递正确的方法或使用Lambdas创建正确的内部类(如)实现。 我认为lambda方式在实现你想要的东西方面更有效率,因为它具有动态性。 这毕竟是他们在那里的原因。