爲什麼此代碼允許獲取類名?使用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