views:

54

answers:

1

I would like to know if it's possible to access the call stack from within a method to see which method in which package called the one we are in now?

Or perhaps there is another way of doing this?

Thanks,

ExtremeCoder

P.S. This is all in Java

+3  A: 

There is a way:

Thread.currentThread().getStackTrace()

But there should not be a reason to do this other than for debug purposes.

Bozho
+1: Certainly shouldn't be changing behavior based on the caller, but that above is exactly how to do get the info. Also, if you're stuck with 1.4 then you have to futz around with exceptions to get the info; it's worth upgrading to Java5 rather than doing those sorts of hacks IMO.
Donal Fellows
Oh, the other case for doing things with stack reading is if you're doing security contexts, but it's really much better to be using the security policy tools you've already got for that instead.
Donal Fellows
The answer is correct, but I disagree about using this just for debug. In my application I wrote a wrapper to the Log4j that sends the logging messages to the appender according to the caller name. So you can add a log message with just one line, without explicitly calling to `Logger.getLogger()` in the code. You can call the logging facility a debug purpose, but anyway.
jutky
This is simply for logging purposes to check who is calling the method and at what time and what is being changed. I think I will be able to parse the stack trace in order to get what I need. Thanks a lot.
ExtremeCoder
@jutky, that is a hack. You cannot rely ón the stacktrace Info being 100% correct. This was discussed a while back ón the logback list.
Thorbjørn Ravn Andersen