Java语法:new之后{}中的语句
这是什么意思Java语法:new之后{}中的语句,java,syntax,Java,Syntax,这是什么意思 addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String location = GUI.Custom.QuickDialogs.selectFile(false); try {
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String location = GUI.Custom.QuickDialogs.selectFile(false);
try
{
PrintWriter pw = new PrintWriter(new File(location));
String text = textArea.getText();
pw.println(text);
pw.flush();
pw.close();
}
catch(Exception ex)
{
textArea.append("Could not save this debug output");
}
}
});
新建ActionListener(){}在{}中发生了什么?在object?类中声明一个方法?ActionListener是内部类吗?新ActionListener()后面的大括号中的声明是扩展ActionListener的定义
在您的例子中,匿名类提供了单个方法
actionPerformed
的实现。当您需要一个只从代码中的一个位置使用的类时,此功能允许您减少代码的大小,并使声明更接近使用声明的位置。使用此语句,您将使用添加的新方法创建新的ActionListener
对象actionPerformed
addActionListener((ActionEvent e) -> {
String location = GUI.Custom.QuickDialogs.selectFile(false);
try
{
PrintWriter pw = new PrintWriter(new File(location));
String text = textArea.getText();
pw.println(text);
pw.flush();
pw.close();
}
catch(Exception ex)
{
textArea.append("Could not save this debug output");
}
});
这相当于创建新类,该类扩展了ActionListener
,例如:
class MyActionListener extends ActionListener {
public void actionPerformed(ActionEvent e) {
// ...
}
}
addActionListener(new MyActionListener());
看看:
这种语法是匿名类,它基本上是覆盖功能的派生类,但由于它仅在此处使用,因此可能不需要命名它
它们的创建原因与lambda语句基本相同,如果某些东西只在代码的一个位置使用,为什么还要麻烦命名它,使类或命名空间变大,污染它。这称为匿名类。通常,它会创建ActionListener接口的新实现,并重载actionPerformed方法 相当于
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e)
{
String location = GUI.Custom.QuickDialogs.selectFile(false);
...
}
}
addActionListener(new MyActionListener())
更多信息可以在中找到,这是一个匿名的内部类,一种简化编写单用途类(通常是接口的实现)的语法糖形式 您可以阅读更多关于它们的信息。匿名内部类”是设置侦听器之类的东西的常用习惯用法。然而,在Java8中,由于
ActionListener
只有一个方法,因此现在可以使用lambda表达式来做同样的事情。编译器将发现您提供的是actionPerformed
的实现
addActionListener((ActionEvent e) -> {
String location = GUI.Custom.QuickDialogs.selectFile(false);
try
{
PrintWriter pw = new PrintWriter(new File(location));
String text = textArea.getText();
pw.println(text);
pw.flush();
pw.close();
}
catch(Exception ex)
{
textArea.append("Could not save this debug output");
}
});
第一行可能是
addActionListener(e -> {
因为编译器将计算出
e
必须是ActionEvent
;不过,人类读者可能会发现,根据他们对AWT的熟悉程度,识别它更为困难。看看:这不是“费心命名”,而是不会用内部函数污染全局名称空间。这是封装,而不是懒惰。是的,这就是我所说的“使类或命名空间更大”的意思。如果你这么喜欢的话,我会加上这个词。