Determining Current Call Stack (For Diagnostic Purposes)

Determining Current Call Stack (For Diagnostic Purposes)

I think you can get the same thing with:

StackTraceElement[] cause = Thread.currentThread().getStackTrace();

How to get Java Call Stack of a running application

Method 1: Use jstack utility from command line (part of the JDK distro).

Method 2: Send signal 3 to the java process, it will dump stack traces on stdout.

Method 3: Call Thread.getAllStackTraces () from within application:

public class StackTraceDumper
{
public static dumpAllStackTraces ()
{
for (Map.Entry <Thread, StackTraceElement []> entry:
Thread.getAllStackTraces().entrySet ())
{
System.out.println (entry.getKey ().getName () + ":");
for (StackTraceElement element: entry.getValue ())
System.out.println ("\t" + element);
}
}
}

Then use StackTraceDumper.dumpAllStackTraces() where you need to dump stack traces.

How can I find the method that called the current method?

Try this:

using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

one-liner:

(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name

It is from Get Calling Method using Reflection [C#].

How to get call hierarchy in java

Try something like this to access the stack of your current thread:

Thread.currentThread().getStackTrace();

This returns an array of StackTraceElement which you then can print or check or do whatever you want.

However, be careful here: If your method behaves differently depending on the caller of your method (e.g by analyzing the stack and reacting on it), you can create some really uncommon and unexpected behaviour for anybode using code like this.

How can we know the caller function's name?

There's nothing you can do only in a.

However, with a simple standard macro trick, you can achieve what you want, IIUC showing the name of the caller.

void a()
{
/* Your code */
}

void a_special( char const * caller_name )
{
printf( "a was called from %s", caller_name );
a();
}

#define a() a_special(__func__)

void b()
{
a();
}


Related Topics



Leave a reply



Submit