Home > Java > javaTutorial > 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
Release: 2024-10-27 06:05:29
Original
396 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template