Accessing the class from a static method which the class owns

Accessing the class from a static method which the class owns is a bit tricky. From a non-static method accessing the class is as simple as doing this.

Class thisClass = this.getClass(); In a static method there are two different ways to access the class. One way, which I learned from this forum discussion, is to create a stack trace and use the fact that the top of the stack trace will have the class we want.
// get stack trace
StackTraceElement[] stackTrace = new Throwable().getStackTrace();

// get the class name at the top level of the stack trace
StackTraceElement stackTraceTopLevelElem = stackTrace[0];
String thisClassName = stackTraceTopLevelElem.getClassName();

// get the class using the class loader
Class thisClass;
try {
  thisClass = Class.forName(thisClassName);
} catch (ClassNotFoundException exc) {
  // this should never happen

The other way is to use Java’s SecurityManager class as described in this article. This way seems preferable because it is not as costly as creating an exception as done in the other way.

Here is some sample code using the SecurityManager. Note that we need to use an inner class because the getClassContext() method is protected.

public static void main(String[] args) {
  Class clazz = new ClassGetter().getClazz();

// inner class is necessary since getClassContext is protected
private static class ClassGetter extends SecurityManager {

  protected ClassGetter() {
    // do nothing

  protected Class getClazz() {
    Class [] classes = getClassContext();
    Class clazz = classes[1];
    return clazz;

Leave a Reply

Your email address will not be published. Required fields are marked *