3 回答

TA贡献1783条经验 获得超4个赞
从技术上讲,没有,因为匿名类不能具有构造函数。
但是,类可以引用包含范围的变量。对于匿名类,这些可以是包含类的实例变量,也可以是标记为final的局部变量。
编辑:正如彼得指出,您还可以将参数传递给匿名类的超类的构造函数。

TA贡献1856条经验 获得超11个赞
是的,通过添加一个返回“ 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) );
无需“最终”声明。

TA贡献1853条经验 获得超6个赞
这会做魔术
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
int myVariable;
public void actionPerformed(ActionEvent e) {
// myVariable ...
}
public ActionListener setParams(int myVariable) {
this.myVariable = myVariable;
return this;
}
}.setParams(myVariable));
添加回答
举报