Getting the class name from a static method in Java Getting the class name from a static method in Java java java

Getting the class name from a static method in Java


In order to support refactoring correctly (rename class), then you should use either:

 MyClass.class.getName(); // full name with package

or (thanks to @James Van Huis):

 MyClass.class.getSimpleName(); // class name and no more


In Java 7+ you can do this in static method/fields:

MethodHandles.lookup().lookupClass()


Do what @toolkit says. Do not do anything like this:

return new Object() { }.getClass().getEnclosingClass();

(Edit: Or if you are using a Java version that came out well after this answer was originally written, @Rein.)