Java, “this” and Inner/Anonymous Classes
Brushing up on my Java for the first time in a while and I came across something fairly trivial but new to me. If you’re a seasoned Javanaut, you’ll have to indulge me for a second :).
When writing a method within an anonymous/inner class in Java, the “this” keyword obviously refers to the anonymous/inner class itself. What if we needed a reference to the instance of the outer class?
public class OuterJFrame extends JFrame {
public OuterJFrame() {
super("Outer/Inner/Anonymous Classes Test");
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
// type error! "this" refers to our ActionListener instance
chooser.showOpenDialog(this);
}
});
}
}
I stumbled across the answer to this little dilemma in the Java SE documentation: it is possible to refer to refer to the instance of the outer class using OuterClass.this:
public class OuterJFrame extends JFrame {
public OuterJFrame() {
super("Outer/Inner/Anonymous Classes Test");
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
// fixed! this works as expected
chooser.showOpenDialog(OuterJFrame.this);
}
});
}
}
Obviously this neat little syntactic tango won’t work with static inner classes, because they are not associated with instances of the outer class. Still useful, yeah?