DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Accessing the class object in a static context

Accessing the class object in a static context

Cedric Beust user avatar by
Cedric Beust
·
Jul. 19, 11 · Java Zone · Interview
Like (0)
Save
Tweet
8.80K Views

Join the DZone community and get the full member experience.

Join For Free

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

Object (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Use Lambda Function URL To Write a Serverless App Backed by DynamoDB
  • Why Is Software Integration Important for Business?
  • Top Six Kubernetes Best Practices for Fleet Management
  • JUnit 5 Tutorial: Nice and Easy [Video]

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo