获取调用栈信息

在Java/Android开发中,在出现异常的时候,通常会调用Exception.printStackTrace();方法获取出现异常时的栈信息。在另外一些情况下,即没有异常,但可能项目涉及的代码量非常大,一时还不明白各个函数的调用关系。比如看到某个方法被调用了,但不清楚它又是被哪个方法调用的。此时可以直接获取当前的调用栈信息,具体方法如下:

StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement e : elements) {
	System.out.println(e.toString());
}

下面是一个实例,定义了一个方法专门打印栈信息:

package com.example.hellolistview;

import android.util.Log;

public class LogUtils {
	public final static String TAG = "LogUtils";
	
	public static void printStackTraces() {
		StackTraceElement[] elements = Thread.currentThread().getStackTrace();
		for (StackTraceElement e : elements) {
			Log.d(TAG, "    " + e.toString());
		}
	}
	
}

调用的地方:

public class MainActivity extends Activity {
	// each item's layout resource id
	private int student_item_id = R.layout.student_item;

	// columns names
	private String[] columnNames = new String[] { "name", "score" };

	// resource ids
	private int[] ids = new int[] { R.id.student_name, R.id.student_score };
	
	private ArrayList<HashMap<String, Object>> students = new ArrayList<HashMap<String, Object>>();
	
	private Context context = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_listview);

        context = this;
        
        ListView listView = (ListView) this.findViewById(R.id.list_view);
        createData();
        //setSimpleAdapter(listView);
        listView.setAdapter(new AnotherAdapter());
        
        LogUtils.printStackTraces();
        
    }

运行效果:



题外话:

如果使用Eclipse加断点进行跟踪,JDT/ADT也会显示出调用栈。需要根据自己的实际情况,选择合适的分析手段。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值