Throwable.fillInStackTrace()的用法

来源:互联网 发布:网络传销一般崩盘时间 编辑:程序博客网 时间:2024/04/19 16:48

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()。

原创粉丝点击