传递功能接口(> = Java的1.8)如果你被允许改变addActionListenerObject
签名:
public class Just {
private ActionListener actionListener;
public void addActionListener(ActionListener actionListener) {
this.actionListener = actionListener;
}
public void doIt() {
System.out.println("Hello");
actionListener.actionPerformed(new ActionEvent(this, 3, "World"));
}
}
public class MyActionListener implements ActionListener {
public void addActionListenerObject(Consumer<ActionListener> consumer) {
consumer.accept(this);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
这样一来,即添加动作监听器(在我的例子中的类,这是Just
)不需要实现一个接口。
使用它:
Just just = new Just();
MyActionListener listener = new MyActionListener();
listener.addActionListenerObject(just::addActionListener); // Aha!
just.doIt();
此打印:
Hello
World
是什么'this'类的定义?扩展/实现了什么类/接口? –
'This'是一个ActionListener – qry