Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Accessing the class object in a static context

DZone's Guide to

Accessing the class object in a static context

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

I often need to access the current class, for example for logging purposes:

public class Foo {
  private Logger logger = LoggerFactory.getLogger(getClass());
}

However, this won’t work in a static context, since you don’t have any this object to call getClass() on:

public class Foo {
  static private Logger logger = LoggerFactory.getLogger(Foo.class);
}

It’s always bothered me to have to copy/paste this line and then remember to replace the name of the class, so here is one way to make this snippet more generic:

public class ClassUtil extends SecurityManager {
 
  public static Class getCurrentClass() {
    return getClassContext()[1];
  }
 
}

Which you use as follows:

public class Foo {
  private static Logger logger = LoggerFactory.getLogger(
      new ClassUtil().getCurrentClass());
}

A somewhat less hacky and cheaper approach is to instantiate an anonymous class in order to materialize a this object:

private static Class thisClass =
    new Object() { }.getClass().getEnclosingClass();
private static Logger logger = LoggerFactory.getLogger(thisClass);

Can you think of any other way?

From http://beust.com/weblog/2011/07/15/accessing-the-class-object-in-a-static-context

Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}