现在的位置: 首页 > 综合 > 正文

Throwable.fillInStackTrace()的用法

2013年12月24日 ⁄ 综合 ⁄ 共 971字 ⁄ 字号 评论关闭

fillInStackTrace这个方法还是很有特点的,竟然能够一直追踪调用自己的那些方法,甚至java的行数,本想仔细看看源代码的,没想到竟然是native的方法,而且api文档中只有一句话,实在是让人很难知道它的真正用法。do了一下research之后,有一些心得。

package exceptions;

public class ThrowableTest3 {
 
 Throwable th =  new Throwable();;
 
 public ThrowableTest3() {
  System.out.println("in constructor");
 }
 
 public void a()
 {
     c();
 }
 
 public void b()
 {
     System.out.println("in b");
     th.fillInStackTrace();
  th.printStackTrace(System.out);
  System.out.println("in b");
 }
 
 public void c()
 {
     b();
     th.fillInStackTrace();
     System.out.println("in c");
     th.printStackTrace(System.out);
  System.out.println("in c");
 }
 

 public static void main(String [] args)
 {
  ThrowableTest3 t3 = new ThrowableTest3();
  t3.a();
 }
}

用printStackTrace(System.out)的原因是为了让打印更加的整洁。

结论:
       fillInStackTrace每次执行的时候,会清空原来的栈内的trace信息。然后在当前的调用位置处重新建立trace信息, 所以在方法b()中printStackTrace的执行结果跟c()中的是不一样的。
       b()方法被c()调用,c()被a()调用,a()被main()调用, 所以在b()中fillInStackTrace时,栈内会包含b(), a(), main()的信息;而在c()中调用fillInStackTrace时,栈内的信息会被刷新为c(), a(), main()。

抱歉!评论已关闭.