傳遞功能接口(> = 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