2

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 ?

1
  • Please don't do this! (With possible exception of debugging, but even there testing would probably be better.) Commented Dec 27, 2011 at 13:04

4 Answers 4

4

Yes: new Throwable().getStackTrace() returns array of StackTraceElement. Index number 1 is your caller.

Sign up to request clarification or add additional context in comments.

2 Comments

+1: Or Thread.currentThread().getStackTrace()
Thanks, but the index I used was 3. Index 1 gives me the name of the class A and the doStuff().
2
/** * <li> 0 dumpThreads * <li> 1 getStackTrace * <li> 2 getCallingMethodName * <li> 3 [calling method] * * @return */ private String getCallingMethodName() { return Thread.currentThread().getStackTrace()[3].getMethodName(); } 

Comments

1

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

0

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.