How to Find the Caller of a Method Using Stacktrace or Reflection

How do I find the caller of a method using stacktrace or reflection?

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

According to the Javadocs:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to experiment to determine which index you want
(probably stackTraceElements[1] or [2]).

Java: How to get the caller function name

You could try

StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
String methodName = e.getMethodName();

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#].

Get caller class and method name

Unfortunately, there is no non-expensive method to do this. There is a Java Enhancement Proposal to add a better alternative, but this doesn't help unless you can wait until Java 9 (and it isn't guaranteed to be included anyway).

On the other hand, is this really a hotspot in your code? This should only matter if it's called in a loop, and in this case you probably can call it once and cache the result.

Identifying the caller method and arguments without reflection

Is that possible without reflection?

No. (I don't even think it's possible with reflection.)

Are there any design pattern that needs to be followed?

The pattern here would be to pass the relevant information as argument to the method. :-)

You could also pass the instance of the Child to the constructor of the Parent, and store the URL as a field in Child.

Parent parent = new Parent(this);  // ...then look up URL through field in Child

Or, you could do use a setter prior to the call to isValidURL:

public void verifyURL(String url) {
parent.setUrl(url);
parent.isValidURL();
}

Regarding your edit:

EDIT: I want to do this because I want to implement the idea on a logger. Basically, there are many other methods like verifyURL() method accepting different parameters. I'd like to have a common logger to print the it on the console when any methods in the `Child' class is called

That clears things up quite a bit.

For this I recommend looking at the current stack trace. I posted a similar solution over here:

  • Include filename/line number corresponding to System.out.print statements in Eclipse Console

What's important to keep in mind for robustness is that you loop through the stack trace until you find the element you're looking for. Even though Parent may internally delegate the call or use isValidUrl as a helper method, it is most likely the calling class (in this case Child) that is of interest. Here's an example that discards the stack elements that are "internal" and prints the name of the calling class/method:

public boolean isValidURL() {
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
if (ste.getClassName().equals(Thread.class.getName())
|| ste.getClassName().equals(getClass().getName()))
continue;
System.out.println(ste.getClassName() + "." + ste.getMethodName());
break;
}
return true;
}

How can I get the caller class object from a method in java?

Get the classname using the code of your linked question: How to get the caller class in Java

Then use the classname to retrieve the class, using code from here: Getting class by its name

Complete code:

String callerName = Thread.currentThread().getStackTrace()[2].getClassName();

try {
Class<?> caller = Class.forName(callerName);
// Do something with it ...
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

(community answer, since only mix of existing answers).



Related Topics



Leave a reply



Submit