Getting the class name from a static method in Jav

2019-08-31 16:31发布

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.

标签: java static
15条回答
我只想做你的唯一
2楼-- · 2019-08-31 16:46

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

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

or (thanks to @James Van Huis):

 MyClass.class.getSimpleName(); // class name and no more
查看更多
We Are One
3楼-- · 2019-08-31 16:47

If you want the entire package name with it, call:

String name = MyClass.class.getCanonicalName();

If you only want the last element, call:

String name = MyClass.class.getSimpleName();
查看更多
forever°为你锁心
4楼-- · 2019-08-31 16:47

I needed the class name in the static methods of multiple classes so I implemented a JavaUtil Class with the following method :

public static String getClassName() {
    String className = Thread.currentThread().getStackTrace()[2].getClassName();
    int lastIndex = className.lastIndexOf('.');
    return className.substring(lastIndex + 1);
}

Hope it will help !

查看更多
▲ chillily
5楼-- · 2019-08-31 16:49

This instruction works fine:

Thread.currentThread().getStackTrace()[1].getClassName();
查看更多
看我几分像从前
6楼-- · 2019-08-31 16:53

In Java 7+ you can do this in static method/fields:

MethodHandles.lookup().lookupClass()
查看更多
你好瞎i
7楼-- · 2019-08-31 16:54

Do what toolkit says. Do not do anything like this:

return new Object() { }.getClass().getEnclosingClass();
查看更多
登录 后发表回答