Lew*_*wis 143 java anonymous-class
是否可以传递参数或访问外部参数到匿名类?例如:
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
}
});
Run Code Online (Sandbox Code Playgroud)
有没有办法让侦听器访问myVariable或传递myVariable而不将侦听器创建为实际的命名类?
Ada*_*ski 328
是的,通过添加一个返回'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) );
Run Code Online (Sandbox Code Playgroud)
不需要"最终"声明.
Mat*_*lis 76
从技术上讲,不,因为匿名类不能有构造函数.
但是,类可以引用包含范围的变量.对于匿名类,这些可以是包含类的实例变量或标记为final的局部变量.
编辑:正如Peter所指出的,您还可以将参数传递给匿名类的超类的构造函数.
ada*_*shr 20
像这样:
final int myVariable = 1;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Now you can access it alright.
}
});
Run Code Online (Sandbox Code Playgroud)
小智 13
这将是神奇的
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));
Run Code Online (Sandbox Code Playgroud)
如http://www.coderanch.com/t/567294/java/java/declare-constructor-anonymous-class所示,您可以添加实例初始化程序.它是一个没有名称并首先执行的块(就像构造函数一样).
看起来他们也在为什么java实例初始化器讨论过?和实例初始化程序如何与构造函数不同?讨论了与构造函数的差异.
我的解决方案是使用一个返回已实现的匿名类的方法.常规参数可以传递给方法,并且可以在匿名类中使用.
例如:(从某些GWT代码处理文本框更改):
/* Regular method. Returns the required interface/abstract/class
Arguments are defined as final */
private ChangeHandler newNameChangeHandler(final String axisId, final Logger logger) {
// Return a new anonymous class
return new ChangeHandler() {
public void onChange(ChangeEvent event) {
// Access method scope variables
logger.fine(axisId)
}
};
}
Run Code Online (Sandbox Code Playgroud)
对于此示例,将使用以下引用新的匿名类方法:
textBox.addChangeHandler(newNameChangeHandler(myAxisName, myLogger))
Run Code Online (Sandbox Code Playgroud)
或者,使用OP的要求:
private ActionListener newActionListener(final int aVariable) {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Your variable is: " + aVariable);
}
};
}
...
int myVariable = 1;
newActionListener(myVariable);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87455 次 |
| 最近记录: |