4

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".

Community
  • 1
  • 1
  • A static method is associated only with the class that it is declared in. It seems to me that there isn't a need to have a way of accessing the class other than explicitly referencing it by name. – Paul Morie Jul 01 '09 at 05:06

3 Answers3

14

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);
  }
}
Chi
  • 22,624
  • 6
  • 36
  • 37
11

You can do it by creating (not throwing) a new Exception and inspecting its stack trace. Your class will be the zeroth element as it is the origin of the Exception. It kinda feels wrong, but it will work.

System.out.println( new Exception().getStackTrace()[0].getClassName() );

You can do the same with the Thread class. This seems cleaner to me, but the line is slightly longer. Your class is now the first element in the stacktrace rather than the zeroth. Thread.getStackTrace() is the zeroth.

System.out.println( Thread.currentThread().getStackTrace()[1].getClassName() );

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

On the contrary, if you rename MyClass using your IDE's refactor function it will replace MyClass.class.getName() with RenamedClass.class.getName(). If you put a string in there you'll have to do it manually.

banjollity
  • 4,490
  • 2
  • 29
  • 32
  • oh... Ok. it's a more secure way, but you have to type the class name anyways. That's what I was trying to avoid. –  Jul 01 '09 at 05:12
  • From your answer and the others', I see the language doesn't provide a clean way to do this, so I dont think it is worth typing such an ugly sentence, considering the few cons typing the classname has (redundancy, mainly). –  Jul 01 '09 at 09:35
1

If it is just a matter of saving some typing, then don't think about it. Using MyClass.class allows all refactoring tools to recognize and work properly with your code.

When you choose to program in Java, you WILL type a lot. Use an IDE which will help you so you don't have to type quite as much :)

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347