Home >Java >javaTutorial >How to Retrieve the Class Name from a Static Method in Java?
Retrieving Class Name from a Static Method in Java
Problem:
How can a static method within a class obtain the name of the class it resides in?
Example:
Consider the following code:
<code class="java">public class MyClass { public static String getClassName() { String name = ????; // what goes here to return "MyClass"? return name; } }</code>
Context:
This knowledge is useful when returning the class name as part of an exception message.
Solution:
To obtain the class name correctly, ensuring proper refactoring support (class renaming), use either:
MyClass.class.getName(); (Full Class Name with Package)
or
MyClass.class.getSimpleName(); (Class Name Only) (thanks to @James Van Huis)
The above is the detailed content of How to Retrieve the Class Name from a Static Method in Java?. For more information, please follow other related articles on the PHP Chinese website!