Tuesday, 19 October 2010

Another JavaFX mistake: LoggerFactory.getLogger(this.getClass())

Every now and then I come across a mistake in our code (either mine or someone else's on the team) that demonstrates something about the JavaFX compiler -- a behaviour that breaks a hidden assumption that programmers sometimes have. Here's another one:

That code's got a potential mistake in it -- if you instantiate a subclass of AlignedContainer, the logger's name won't be AlignedContainer, but the name of the subclass. In JavaFX, the compiler generates subclasses for object literals, and you'll find that many of your loggers are named after generated classes.

So, in this particular case the logger ended up being


Which is a more awkward to turn on or off individually using log4j.properties (notice that one of the generated parts of the name, "TimelineGui$1", comes before "AlignedContainer"). Why is this the case? Well, the AlignedContainer was instantiated using an object literal:

The JavaFX compiler neatly generates an inner class extending AlignedContainer to implement this object literal:

So then it makes sense that this.getClass() does not return the AlignedContainer class but this anonymous inner class.

No comments: