By running Java 5.0, you can use Thread.currentThread().getStackTrace()
to get the current stack trace.
To get the class (and method) of the current call to the current method:
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); int i = 1; while (MyClass.class.getName().equals(stackTraceElements[i].getClassName())) { i++; } int lineNumber = stackTraceElements[i].getLineNumber(); String className = stackTraceElements[i].getClassName(); String methodName = stackTraceElements[i].getMethodName();
Note! There are some warnings in javadocs regarding this method:
Some virtual machines may, in some circumstances, omit one or more stack frames from a stack trace. In extreme cases, a virtual machine that does not have stack trace information related to this thread is allowed to return a zero-length array from this method.
I have no problem with this piece of code on the Sun (Oracle) JVM JVM and Mac OS X JVM. Please test your code carefully to make sure that it works as you expect, especially if you use any other JVM.
source share