Home > Java, programming, regular > X.this in Java

X.this in Java


I don’t know how I missed out on this information, but there’s a very useful construct in Java when dealing with inner classes.

Say we have the following:

public class A {
	private JButton button;

	public A() {
		button = new JButton("Push me");

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

			}
		});
	}
}

How do we reference the instance of A from within the anonymous ActionListener? Before I learned this, I would have done the following:

public class A {
	private JButton button;

	public A() {
		button = new JButton("Push me");
		final A theInstance = this;
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			      System.out.println("The instance holding me is " + theInstance);
			}
		});
	}
}

But there’s a better way to do this, without having to declare any new variables:

public class A {
	private JButton button;

	public A() {
		button = new JButton("Push me");

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			    System.out.println("The instance holding me is " + A.this);
			}
		});
	}
}

Very cool!

Advertisements
Categories: Java, programming, regular
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: