如何从该类的静态方法中获取该类的名称。例如

public class MyClass {
    public static String getClassName() {
        String name = ????; // what goes here so the string "MyClass" is returned
        return name;
    }
}

为了把它放在上下文中,我实际上想在异常中返回类名作为消息的一部分。


当前回答

我需要在多个类的静态方法中的类名,所以我用下面的方法实现了一个JavaUtil类:

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

希望对大家有所帮助!

其他回答

滥用SecurityManager

System.getSecurityManager().getClassContext()[0].getName();

或者,如果没有设置,使用一个内部类来扩展它(下面的例子可耻地复制自Real的HowTo):

public static class CurrentClassGetter extends SecurityManager {
    public String getClassName() {
        return getClassContext()[1].getName(); 
    }
}

如果你正在使用反射,你可以获取Method对象,然后:

method.getDeclaringClass().getName()

要获取方法本身,您可以使用:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)

如果你想要整个包的名称,调用:

String name = MyClass.class.getCanonicalName();

如果你只想要最后一个元素,调用:

String name = MyClass.class.getSimpleName();

我使用它在类的顶部初始化Log4j Logger(或注释)。

优点:Throwable已经加载,你可能会节省资源,不使用“IO重型”安全管理器。

反:有些问题是,这是否适用于所有jvm。

// Log4j . Logger --- Get class name in static context by creating an anonymous Throwable and 
// getting the top of its stack-trace. 
// NOTE you must use: getClassName() because getClass() just returns StackTraceElement.class 
static final Logger logger = Logger.getLogger(new Throwable() .getStackTrace()[0].getClassName()); 

这条指令工作得很好:

Thread.currentThread().getStackTrace()[1].getClassName();