如何从该类的静态方法中获取该类的名称。例如
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;
}
}
为了把它放在上下文中,我实际上想在异常中返回类名作为消息的一部分。
当前回答
如果你正在使用反射,你可以获取Method对象,然后:
method.getDeclaringClass().getName()
要获取方法本身,您可以使用:
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod ("method name", parameterTypes)
其他回答
一种重构安全、剪切和粘贴安全的解决方案,避免了下面定义的临时类。
写一个恢复类名的静态方法,注意在方法名中包含类名:
private static String getMyClassName(){
return MyClass.class.getName();
}
然后在你的静态方法中召回它:
public static void myMethod(){
Tracer.debug(getMyClassName(), "message");
}
重构安全性是通过避免使用字符串来实现的,剪切和粘贴安全性是被授予的,因为如果你剪切和粘贴调用者方法,你将在目标“MyClass2”类中找不到getMyClassName(),所以你将被迫重新定义和更新它。
这条指令工作得很好:
Thread.currentThread().getStackTrace()[1].getClassName();
滥用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)
按照@toolkit说的去做。不要做这样的事情:
return new Object() { }.getClass().getEnclosingClass();
(编辑:或者如果你使用的Java版本是在这个答案最初写出来之后才出现的,使用@Rein的答案。)