I have class X and in it there is a static method called doStuff() and I have several other classes with methods that call to doStuff() for some reason. Is there a way for example to have a print method in doStuff() that prints from which methods and classes it is called ?
- Please don't do this! (With possible exception of debugging, but even there testing would probably be better.)Tom Hawtin - tackline– Tom Hawtin - tackline2011-12-27 13:04:21 +00:00Commented Dec 27, 2011 at 13:04
Add a comment |
4 Answers
Yes: new Throwable().getStackTrace() returns array of StackTraceElement. Index number 1 is your caller.
2 Comments
Peter Lawrey
+1: Or
Thread.currentThread().getStackTrace()nyxz
Thanks, but the index I used was 3. Index 1 gives me the name of the class A and the doStuff().
You can get the caller class using:
package test; class TestCaller { public static void meth() { System.out.println("Called by class: " + sun.reflect.Reflection.getCallerClass(2)); } } public class Main { public static void main(String[] args) { TestCaller.meth(); } } Output: "Called by class: class test.Main"
Comments
You don't need to force an Exception in order to do this. Check this similar question:
Is there a way to dump a stack trace without throwing an exception in java?