从Java中的静态方法获取类名 [英] Getting the class name from a static method in Java
本文介绍了从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
这篇关于从Java中的静态方法获取类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文