从Java中的静态方法获取类名
问题描述:
如何从该类中的静态方法获取类的名称。例如
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.
答
为了正确支持重构(重命名类),那么你应该使用:
In order to support refactoring correctly (rename class), then you should use either:
MyClass.class.getName(); // full name with package
或(感谢 @ James Van Huis ):
MyClass.class.getSimpleName(); // class name and no more