Home  >  Article  >  Java  >  How to Retrieve the Class Name from a Static Method in Java?

How to Retrieve the Class Name from a Static Method in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 06:05:29301browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn