首页 > 解决方案 > 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)

我真的希望我说清楚了!谢谢

标签: java

解决方案


编译器不知道!;-)
它是在运行时Timer创建实例的实例,并且实例将调用它创建的方法。ActionEventdelayTimerActionListeneractionPerformedActionEvent

您可以在这里查看其中一个实现: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"));
}

推荐阅读