Starting Java 5.0, you can use Thread.currentThread().getStackTrace()
to get a current stack trace.
To get caller class (and method) of 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();
Please note! There is some kind of warning in javadocs regarding this method:
Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.
I have not any trouble with this piece of code on Sun (Oracle) JVM and Mac OS X JVM. Please test your code carefully to be sure it works like you expect, especially if you use any other JVM.