Real'sHowTo AddThis Feed Button
Custom Search

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


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();
    }
  }
}
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
    */
 }
}


blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2013
[ home ]