在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也会显示出调用栈。需要根据自己的实际情况,选择合适的分析手段。