如何从该类的静态方法中获取该类的名称。例如
public class MyClass {
public static String getClassName() {
String name = ????; // what goes here so the string "MyClass" is returned
return name;
}
}
为了把它放在上下文中,我实际上想在异常中返回类名作为消息的一部分。
如何从该类的静态方法中获取该类的名称。例如
public class MyClass {
public static String getClassName() {
String name = ????; // what goes here so the string "MyClass" is returned
return name;
}
}
为了把它放在上下文中,我实际上想在异常中返回类名作为消息的一部分。
当前回答
这条指令工作得很好:
Thread.currentThread().getStackTrace()[1].getClassName();
其他回答
按照@toolkit说的去做。不要做这样的事情:
return new Object() { }.getClass().getEnclosingClass();
(编辑:或者如果你使用的Java版本是在这个答案最初写出来之后才出现的,使用@Rein的答案。)
滥用SecurityManager
System.getSecurityManager().getClassContext()[0].getName();
或者,如果没有设置,使用一个内部类来扩展它(下面的例子可耻地复制自Real的HowTo):
public static class CurrentClassGetter extends SecurityManager {
public String getClassName() {
return getClassContext()[1].getName();
}
}
因为问题是' this.class '而不是' ClassName.class ' ?被标记为这个的重复(这是有争议的,因为这个问题是关于类而不是类名),我在这里发布答案:
class MyService {
private static Class thisClass = MyService.class;
// or:
//private static Class thisClass = new Object() { }.getClass().getEnclosingClass();
...
static void startService(Context context) {
Intent i = new Intent(context, thisClass);
context.startService(i);
}
}
将thisClass定义为private很重要,因为: 1)它不能被继承:派生类必须要么定义自己的thisClass,要么产生错误消息 2)其他类的引用应该使用ClassName.class而不是ClassName.thisClass。
定义了thisClass后,对类名的访问变为:
thisClass.getName()
我使用它在类的顶部初始化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());
为了正确地支持重构(重命名类),那么你应该使用:
MyClass.class.getName(); // full name with package
或者(感谢@James Van Huis):
MyClass.class.getSimpleName(); // class name and no more