Get the class name in a static method

From CodeCodex

Implementations[edit]

Java[edit]


public class ClassFromStatic {

  public static void main(java.lang.String[] args) {
    someStaticMethod();
  }

  public static void someStaticMethod() {
    System.out.println
       ("I'm in " + new CurrentClassGetter().getClassName() + " class");
  }

  public static class CurrentClassGetter extends SecurityManager {
    public String getClassName() {
      return getClassContext()[1].getName();
    }
  }
}

Alternatively:

public class ClassFromStatic {

    public static void main(java.lang.String[] args) {
        someStaticMethod();
    }

    public static void someStaticMethod() {
        System.out.println
            ("I'm in " + new CurrentClassGetter().getClassName() + " class");
    }

    public static class CurrentClassGetter {
        public String getClassName() {
            return Thread.currentThread().getStackTrace()[2].getClassName();
        }
    }
}