是否可以向匿名类传递参数或访问外部参数?例如:
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
}
});
侦听器是否有任何方式访问myVariable或传递myVariable而不将侦听器创建为实际的命名类?
从技术上讲,不可以,因为匿名类不能有构造函数。
但是,类可以从包含作用域引用变量。对于匿名类,这些变量可以是包含类(ES)中的实例变量,也可以是标记为Final的局部变量。
您还可以将参数传递给匿名类的超类的构造函数。
是的,通过添加返回“this”的初始化程序方法,立即调用该方法:
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
private int anonVar;
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
// It's now here:
System.out.println("Initialized with value: " + anonVar);
}
private ActionListener init(int var){
anonVar = var;
return this;
}
}.init(myVariable) );
不需要最后的声明。