Get the Stack trace information in Java SE 5.0
JAVA SE 5.0 provides two very useful APIs to help us debug our program, All this two are all class "Thread"’s method:
public StackTraceElement[] getStackTrace()
Returns an array of stack trace elements representing the stack dump of this thread. This method will return a zero-length array if this thread has not started or has terminated. If the returned array is of non-zero length then the first element of the array represents the top of the stack, which is the most recent method invocation in the sequence. The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
public static Map<Thread, StackTraceElement[]> getAllStackTraces()
Returns a map of stack traces for all live threads. The map keys are threads and each map value is an array of StackTraceElement that represents the stack dump of the corresponding Thread.
We can use this two APIs to get the thread’s stack trace information and help us debug or log. I will give a example that use this to write log.
If we are going to add log before, we need to add a "java.util.logging.Logger" to our class and use it to log. It’s ok and works pretty well, the following code just wanna to give you an example of the new exposed API "getStackTrace".
- public static void log(Level level, String message) {
- Thread currentThread = Thread.currentThread();
- StackTraceElement[] sts = currentThread.getStackTrace();
- if (sts != null && sts.length > 3) {
- StackTraceElement ste = sts[3];
- String fileName = ste.getFileName();
- String className = ste.getClassName();
- String methodName = ste.getMethodName();
- int lineNum = ste.getLineNumber();
- LogRecord record = new LogRecord(level, message + "At line " + lineNum + " in file " + fileName);
- record.setSourceClassName(className);
- record.setThreadID((int) currentThread.getId());
- record.setSourceMethodName(methodName);
- logger_.log(record);
- } else {
- logger_.log(level, message);
- }
- }
Caught the meaning? Yes, it’s pretty simple.
sts[0] = java.lang.Thread :: dumpThreads
sts[1] = java.lang.Thread :: getStackTrace
sts[2] = LogTest :: log ( This function )
sts[3] = Where you called the log function
And you can use this stack trace information to finish other features.
Popularity: 35% [?]
Related entries:
October 24th, 2005 at 10:51 am
You can also get stack trace by (new Throwable()).getStackTrace(), which was presented in Java SE 1.4.
October 24th, 2005 at 11:03 am
Yes, and the new API’s point is to get the *specific* thread’s stack trace.
October 25th, 2005 at 9:34 am
你被点名了http://spaces.msn.com/
members/jianxin-liang/Blog
/cns!1ptK9M_fmx0DPL0i8DelgRKA!
275.entry?owner=1
October 25th, 2005 at 4:52 pm
请问您的Java代码是怎么变色贴上去的,是WP的插件吗?
October 26th, 2005 at 3:47 pm
对,搜一下CoolCode插件。