/** * Static class of "helper" methods for easily obtaining backtraces. */ public class Backtrace { /** * Retrieve the stacktrace by sending an exception, catching it * and getting its stacktrace. */ private static StackTraceElement[] getStackTrace() { try { throw new Exception(); } catch ( Exception e ) { return e.getStackTrace(); } } /** * Returns the full backtrace corresponding to the StackTraceElement's * passed. This is useful to get the backtrace from a catch block. */ public static String backtraceFull( StackTraceElement[] trace ) { StringBuffer sb = new StringBuffer(); for ( int i = 2; i < trace.length; i++ ) { sb.append( "\t" ).append( trace[i].toString() ).append( "\n" ); } return sb.toString(); } /** * Returns the full backtrace of the caller method. */ public static String backtraceFull() { return Backtrace.backtraceFull( Backtrace.getStackTrace() ); } /** * Returns the backtrace corresponding to the StackTraceElement's * passed, limited to my classes. This is useful to get the * backtrace from a catch block. */ public static String backtrace( StackTraceElement[] trace ) { StringBuffer sb = new StringBuffer(); for ( int i = 2; i < trace.length && trace[i].toString().startsWith( "org.gc" ); i++ ) { sb.append( "\t" ).append( trace[i].toString() ).append( "\n" ); } return sb.toString(); } /** * Returns the backtrace of the caller method, limited to mnc classes. */ public static String backtrace() { return Backtrace.backtrace( Backtrace.getStackTrace() ); } }