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.
This instruction works fine:
Abuse the SecurityManager
Or, if not set, use an inner class that extends it (example below shamefully copied from Real's HowTo):
If you are using reflection, you can get the Method object and then:
To get the Method itself, you can probably use:
In Java 7+ you can do this in static method/fields:
Verbatim use of caller's class like
MyClass.class.getName()
actually does the job, but is prone to copy/paste errors if you propagate this code to numerous classes/subclasses where you need this class name.And Tom Hawtin's recipe is in fact not bad, one just needs to cook it the right way :)
In case you have a base class with a static method that may be called from subclasses, and this static method needs to know the actual caller's class, this may be achieved like the following:
A refactoring-safe, cut&paste-safe solution that avoids the definition of ad-hoc classes below.
Write a static method that recover the class name having care to include the class name in the method name:
then recall it in your static method:
Refactoring safety is given by avoiding the use of strings, cut&paste safety is granted because if you cut&paste the caller method you won't find the getMyClassName() in the target "MyClass2" class, so you will be forced to redefine and update it.