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 ?
Asked
Active
Viewed 174 times
1

nyxz
- 6,918
- 9
- 54
- 67
-
Please don't do this! (With possible exception of debugging, but even there testing would probably be better.) – Tom Hawtin - tackline Dec 27 '11 at 13:04
4 Answers
4
Yes: new Throwable().getStackTrace()
returns array of StackTraceElement
. Index number 1 is your caller.

AlexR
- 114,158
- 16
- 130
- 208
-
1
-
Thanks, but the index I used was 3. Index 1 gives me the name of the class A and the doStuff(). – nyxz Dec 27 '11 at 13:16
2
/**
* <li> 0 dumpThreads
* <li> 1 getStackTrace
* <li> 2 getCallingMethodName
* <li> 3 [calling method]
*
* @return
*/
private String getCallingMethodName() {
return Thread.currentThread().getStackTrace()[3].getMethodName();
}

A4L
- 17,353
- 6
- 49
- 70
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"

rmist
- 463
- 1
- 6
- 15
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?