What if I made an explicit reference to 'this' for use inside an inner class?
So far, I've used this approach to access this
from the scope of an inner class:
class FooManagementWindow extends JFrame {
JButton rejectFoo;
//...
void getFooAcceptingPanel(){
//...
final FooManagementWindow referenceToThis = this;
rejectFoo = new JButton("Reject");
rejectFoo.addEventListener(new EventListener() {
@Override
public void actionPerformed(ActionEvent arg) {
referenceToThis.setEnabled(false); //this requires a network call
//...
referenceToThis.setEnabled(true); //the user may resume his work
}
});
//...
}
}
However, I just learned that instead of declaring referenceToThis
, a direct reference is kept for me as:
FooManagementWindow.this
I have no reason to think my less standard approach may lead to er开发者_运维知识库rors or weird corner cases. Or are there?
There is nothing 'wrong' with the way you have been doing it (besides the fact that it is nonstandard). It is essentially the same thing that the Java compiler does behind the scenes for you.
It's fine, except for it makes your listeners larger by one reference. No problem unless you have many thousands of them.
Actually, if you use neither FooManagementWindow.this
nor anything from the enclosing instance, the compiler could theoretically eliminate the unused reference and than your approach would be for free. I'm not sure, if it is allowed to do so and I doubt it does it. The debugger says it doesn't.
Just to point you in another direction. You could always change this:
rejectFoo.addEventListener(new EventListener() {
@Override
public void actionPerformed(ActionEvent arg) {
referenceToThis.setEnabled(false); //this requires a network call
//...
referenceToThis.setEnabled(true); //the user may resume his work
}
});
to this:
rejectFoo.addEventListener(new EventListener() {
@Override
public void actionPerformed(ActionEvent arg) {
rejectFooActionPerformed(arg);
}
});
// ... after the getFooAcceptingPanel() method
public void rejectFooActionPerformed(ActionEvent arg) {
setEnabled(false); //this requires a network call
//...
setEnabled(true); //the user may resume his work
}
This works because you can call a this.method from your inner class and then when you write all of your action code in this method, you are in the scope of your class and not the inner class so you don't need to do what you were stating.
Just food for thought, I always prefer this approach as it's a bit cleaner. Putting all your code in an anonymous inner class is messy and not good practice.
精彩评论