java - Java,编译器如何知道在这个 lambda 表达式中调用哪个构造函数
问题描述
我有一个问题,我正在用一本书学习 java,当我在那里复制了一些代码(并进行了一些更改)并进行了一些调查时,我发现了一些奇怪的东西......,这是代码
public static void main(String[] args)
{
Timer timer = new Timer(1000, (event) ->
{
System.out.println("At the Tone, the time is" + Instant.ofEpochMilli(event.getWhen()));
Toolkit.getDefaultToolkit().beep();
});
timer.start();
JOptionPane.showMessageDialog(null, "Quit?");
System.exit(0);
}
它只是一个代码,如果第二次通过,它会通知您。(这段代码编译运行流畅)
如您所见,Timer Constructor 需要 2 个 pars (int, ActionListener)
public Timer(int delay, ActionListener listener)
并且 ActionListener 接口有一种方法是 actionPerformed 并且需要 ActionEvent 参数
public void actionPerformed(ActionEvent e);
现在这是我的问题,当在上面的那个 lambda 表达式中调用这个 actionPerformed 方法时,编译器如何知道要调用哪个构造函数来实例化 ActionEvent 而没有给他任何关于参数的线索,ActionEvent 没有“无参数构造函数”和方法 getWhen( ) 不是静态的(obj 必须被实例化)
以下是 ActionEvent 的所有构造函数:
public ActionEvent(Object source, int id, String command)
public ActionEvent(Object source, int id, String command, int modifiers)
public ActionEvent(Object source, int id, String command, long when,
int modifiers)
我真的希望我说清楚了!谢谢
解决方案
编译器不知道!;-)
它是在运行时Timer
创建实例的实例,并且实例将调用它创建的方法。ActionEvent
delay
Timer
ActionListener
actionPerformed
ActionEvent
您可以在这里查看其中一个实现:http:
//developer.classpath.org/doc/javax/swing/Timer-source.html
/**
* Fire the action event, named "Timer" and having the numeric
* identifier, equal to the numer of events that have been
* already fired before.
*/
void fireActionPerformed()
{
fireActionPerformed(new ActionEvent(this, ticks++, "Timer"));
}
推荐阅读
- azure - 无法通过在 ADF 中创建的 Azure SSIS /SSIS 运行时使用 Windows 身份验证连接到 azure 多维数据集
- google-chrome - Google Chrome 扩展在活动选项卡中获取页面的详细信息
- tensorflow - 如何从 make_csv_dataset 中获取编码器?
- excel - Selenium 数据驱动测试 - 无法从 Numbers 应用程序 (macOS) 获取数据
- python - 指定尺寸时,使用 GPU 的 torch.max 比使用 CPU 慢
- keras - 使用 ResNet50 进行迁移学习 - 验证结果良好,但生产结果不佳
- android - onNext() 方法只被调用一次
- ionic-framework - 如何在 Ionic 4 的侧边菜单中管理会话?
- java - 如何定期在两种颜色之间进行矩形更改?
- python - Python Tensorflow session.run() 发布 GIL