How can one get the name of the class from a static method in that class. For example
public class MyClass {
public static String getClassName() {
String name = ????; // what goes here so the string "MyClass" is returned
return name;
}
}
To put it in context, I actually want to return the class name as part of a message in an exception.
In order to support refactoring correctly (rename class), then you should use either:
or (thanks to @James Van Huis):
If you want the entire package name with it, call:
If you only want the last element, call:
I needed the class name in the static methods of multiple classes so I implemented a JavaUtil Class with the following method :
Hope it will help !
This instruction works fine:
In Java 7+ you can do this in static method/fields:
Do what toolkit says. Do not do anything like this: