如何在静态方法中获取当前类名

When you produce logging or debugging messages, you often want to include the name of the current class, such as

System.err.println("Something awful happened in " + getClass());

But that fails in a static method. After all, the call to getClass calls this.getClass(), and a static method has no this. Use the following expression instead:

new Object(){}.getClass().getEnclosingClass() // gets class of static method

Here, new Object(){} makes an anonymous object of an anonymous subclass of Object, and getEnclosingClass gets its enclosing class—that is, the class containing the static method.

你可能感兴趣的:(如何在静态方法中获取当前类名)