Michael HönnigMichael Hönnig
Der aktuelle Stacktrace kann in Java ganz einfach mit Thread.currentThread().getStackTrace(); ermittelt werden. Doch darin enthalten ist dann auch die Methode getStackTrace() selbst. Diese kleine Hilfklasse schneidet diesen irrelvanten Teil des Stacktraces ab:
/// convenience class to access the current stack trace
public class StackTrace {

 private static final int classLen = "class".length();
 private static final String clazz = 
     StackTrace.class.toString().substring(classLen+1);

 private StackTraceElement[] stack;
 private int offset;

 /// takes a snapshot of the current stack trace
 public StackTrace() {
   stack = Thread.currentThread().getStackTrace();
   offset = 0;
   while ( !clazz.equals(stack[offset].getClassName()) ) {
     ++offset;
   }
   while ( clazz.equals(stack[offset].getClassName()) ) {
     ++offset;
   }
 }

 /** returns the n-th stack trace element, 
      only counting frames above this class itself **/
 public StackTraceElement getStackTrace(int n) {
  return stack[n+offset];
 }
}
Verwendet wird die Klasse, wie in folgendem kleinen JUnit Test dargestellt:
import org.junit.Test;
import static org.junit.Assert.*;

public class StackTraceTest {

 @Test
 public void getStackTraceTest() {
 test1();
 }

 private static void test1() {
 test2();
 }

 private static void test2() {
 StackTrace trace = new StackTrace();

 StackTraceElement frame0 = trace.getStackTrace(0); 
 assertEquals( "test2", frame0.getMethodName().toString() );

 StackTraceElement frame1 = trace.getStackTrace(1);  
 assertEquals( "test1", frame1.getMethodName().toString() );
 }    
}