为什么此代码允许获取类名?使用Throwable获取类名称
我宣布与静态方法的类(它时并不需要必须是静态的BTW)
class JavaSample {
public static String getClassName() {
final Throwable t = new Throwable();
t.fillInStackTrace();
final String clazz = t.getStackTrace()[1].getClassName();
return clazz;
}
}
如果我接着写
public class HelloWorld{
public static void main(String []args){
System.out.println(JavaSample.getClassName());
}
}
它返回HelloWorld
类名。但是,如果我不喜欢这个
public class HelloWorld{
public static void main(String []args){
final Throwable t = new Throwable();
t.fillInStackTrace();
final String clazz = t.getStackTrace()[1].getClassName();
System.out.println(clazz);
}
}
它抛出线t.getStackTrace()[1]
ArrayIndexOutOfBoundsException
。
为什么在我使用Throwable
时返回classname?
我想这是因为你实际上没有一个调用堆栈?主执行已经在基础级别上了? – vegaasen