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
Example Images For Code and Mark-Up Q&As
Find Div Element by Multiple Class Names
How to Return Datasnapshot Value as a Result of a Method
How to Create Recyclerview With Multiple View Types
Download a File With Android, and Showing the Progress in a Progressdialog
How to Pass an Object from One Activity to Another on Android
Setting Singleton Property Value in Firebase Listener
How to Launch an Activity from Another Application in Android
View'S Getwidth() and Getheight() Returns 0
How to Call a Method After a Delay in Android
Create a File from a Photo Uri on Android
Manipulating an Access Database from Java Without Odbc
Including All the Jars in a Directory Within the Java Classpath
Cannot Make a Static Reference to the Non-Static Method
How to Retrieve and Display Images from a Database in a Jsp Page
How to Invoke a Java Method When Given the Method Name as a String