I am having real trouble tracking down a bug and it would help be a lot to know which method called a certain method. Is there an easy way to get a call hierarchy from java? Java is a small part of the app so I cannot compile and run the whole app in eclipse/net beans so I don't have access to an IDE debugger's call hierarchy.
-
It sounds like you really want a stack trace, not a call hierarchy. (Is it possible to edit a question's Subject?) – Stephen C Jul 28 '09 at 23:52
-
A stack trace is a call hierarchy unless I'm missing some subtle difference. – Bill K Jul 29 '09 at 01:19
-
1A call heirarchy is a TREE of all the places that a procedure can be called from. – Stephen C Jul 29 '09 at 03:48
-
I have to agree with Stephen C, what you're refering to is called a stack trace. – Steve Kuo Jul 31 '09 at 15:24
4 Answers
Thread.currentThread().getStackTrace();
or
Exception ex = new Exception();
ex.printStackTrace();
It's fairly slow, but fine for debugging purposes. API docs here.

- 27,541
- 5
- 35
- 31
Java is a small part of the app so I cannot compile and run the whole app in eclipse/net beans so I don't have access to an IDE debugger's call hierarchy.
You dont need to run the app at all. If you make a project in Eclipse, you can use its built-in Call Hierarchy tool to find all of the possible places that call a method.
There is a trade off: The Call Hierarchy tool will give you ALL of the places from where a method is called. This is a good if you want/need to know all the possibilities. Neslson's suggestion of Thread.currentThread().getStackTrace()
will give you the places from where a method is invoked during the process of you program for this invocation. The nuance is that you might not run through every code path during this invocation. If you are seeing specific behavior and want to know how you got there, use the getStackTrace()
option.

- 38,619
- 8
- 86
- 96
Have you tried using Java's remote debugging capability? Google search to get you started if you haven't

- 3,634
- 1
- 25
- 36
The best thing to do is throw an exception, immediately catch it and analyze the stack trace.
I believe that is how Log4J is capable of logging the calling method.

- 2,255
- 1
- 24
- 36
-
2with Thread.dumpStack() or some such no need to throw an artificial exception. – djna Jul 28 '09 at 23:17
-
You are correct that this is the way that log4j does it. I think thisi just for historical reasons though, since Java 1.5 the currentThread().getStackTrace() method suggested by Nelson is available so this approach is no longer necessary. – mikej Jul 28 '09 at 23:19