Is it possible to get the class name from a static method?

javanewbie picture javanewbie · Jul 1, 2009 · Viewed 8.4k times · Source

Possible Duplicate:
Getting the class name from a static method in Java

When you are inside of a static method, is there a way to get the class name (a string containing the name) without typing the class name itself?

For example, typing MyClass.class.getName() is no more useful than just "Myclass".

Answer

Chi picture Chi · Jul 1, 2009

You can use an anonymous inner class:

class Test {
  public static void main(String[] args) {
    String className = new Object(){}.getClass().getEnclosingClass().getName();
    System.out.println(className);
  }
}