Getting the class name from a static method in Java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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.

Answers

In order to support refactoring correctly (rename class), then you should use either:

 MyClass.class.getName(); // full name with package

http://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java/936715#936715 http://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java/936715#936715

 MyClass.class.getSimpleName(); // class name and no more

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils