I've got 2 functions within the same class, say function_1()
and function_2()
in the following structure;
public class JavaClass {
function_1() {
if (wasCalledbyfunction_2()) {
... do something
}
...
}
function_2() {
function_1()
...
}
I'm having trouble finding a way to implement the wasCalledbyfunction_2()
method. That is, if function_1 was called by function 2, I want to change the behaviour of the former.
I've tried looking into using the in-built Stack Trace methods but I'm lacking some clarity on how to actually implement it.
Any help is appreciated!
CodePudding user response:
You can use : StackTraceElement.getMethodName()
, the call of this method returns the name of the method containing the execution point represented by this stack trace element.
public class JavaClass {
void function_1() {
StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
if (stackTraceElements[1].getMethodName().equals("function_2")) {
System.out.println("Called by function_2");
} else {
System.out.println("Called by another method !");
}
}
void function_2() {
function_1();
}
void function_3() {
function_1();
}
public static void main(String[] args) {
new JavaClass().function_2();
new JavaClass().function_3();
}
}
Output :
Called by function_2
Called by another method !
stackTraceElements[0].getMethodName()
will contain the current method name : function_1
stackTraceElements[2].getMethodName()
will contain the caller method name : function_2
stackTraceElements[3].getMethodName()
will contain the first caller method name : main