Share this page 

Get the class name in a static methodTag(s): Language


The hard-coded way
package com.rgagnon.howto;

public class Test {
  public static void main(String[] args) throws Exception {
    System.out.println (Test.class.getSimpleName());
    System.out.println (Test.class.getCanonicalName());
    System.out.println (Test.class.getName());
    /*
     output :
     Test
     com.rgagnon.howto.Test
     com.rgagnon.howto.Test
    */
 }
}
The dynamic way
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(); // can be .getSimpleName() to get
                                             // the class name without the package
    }
  }

  /*
  output :
  I'm in com.rgagnon.howto.ClassFromStatic class
  */

}