Peeks and Pokes Hey, what does this button do?

2Aug/100

Getting rid of synthetic accessors when using inner classes

The sample code below will generate a "Read access to enclosing field MyRunnableFactory.log is emulated by a synthetic accessor method" warning within the Runnable inner class:

public class MyRunnableFactory {
	private final Logger log = Logger.getLogger("MyRunnableFactory");

	public Runnable makeRunnable() {
		return new Runnable() {
			@Override
			public void run() {
				// the log variable below shows the
				// synthetic accessor method warning
				log.info("Doing fun stuff");
			}
		};
	}
}

I've seen many posts on the web that suggest we ignore or suppress the warning, and just deal with the performance hit. A quick hack can rid you of this annoying warning, while also getting rid of the synthetic accessor (and its performance hit):

public class MyRunnableFactory {
	private final Logger log = Logger.getLogger("MyRunnableFactory");

	public Runnable makeRunnable() {
		// localize the instance field
		final Logger log = this.log;

		return new Runnable() {
			@Override
			public void run() {
				// the synthetic accessor is no longer needed!
				log.info("Doing fun stuff");
			}
		};
	}
}

Let's hope that a future version of the java compiler is smart enough to locally alias so we don't have to muddy our code ;)
Православни икони

Filed under: Java No Comments