1

I noticed when looking through some of the Java code at my work that when we initialise the logging framework in each class we have something like:

private final Logger log = Logger.getLogger(Foo.class);

This got me thinking, is there any reason that we use Foo.class rather than:

private final Logger log = Logger.getLogger(this.getClass());

Is this simply a preference or is there a practical reason to prefer one over the other?

Edit: originally the code snippets referenced static members, which obviously wouldn't have compiled.

Matt Watson
  • 5,065
  • 4
  • 30
  • 48
  • See also http://stackoverflow.com/questions/10725402/generic-way-of-getlogger-from-log4j-logger – Alex Shesterov May 03 '16 at 19:27
  • If you were in a non-static context, you would be able to use either, but they are of different type: `Foo.class` is of type `Class`; `aFoo.getClass()` is of type `Class extends Foo>`. – Andy Turner May 03 '16 at 19:29
  • My bad, I copy and pasted the logging code and didn't notice the `static` in there. That wasn't intended. I'll edit the original question. – Matt Watson May 03 '16 at 19:30
  • 1
    The duplicate explains the difference between the two expressions. There are quite a few other posts about loggers specifically: [here](http://stackoverflow.com/questions/6653520/why-do-we-declare-loggers-static-final), [here](http://stackoverflow.com/questions/3842823/should-logger-be-private-static-or-not), and more. – Sotirios Delimanolis May 03 '16 at 19:32

1 Answers1

3

Ignoring the bit about static contexts (which is totally correct - let's assume your expressions in those initializers get moved to instance methods instead) - a method with this.getClass() will have very different results when called from a subclass!

If you want the class object for Foo, always, use the first version.

If you want the class of the caller (a subclass of Foo), use the second version.

BadZen
  • 4,083
  • 2
  • 25
  • 48