IMPORTANT : THE EXAMPLE IS WRONG, I EXPLAIN WHY AT THE BOTTOM
As the title stated the question is about to define a way to determine when the current executing method is invoked in a recursively way.
I have think about having a "query method" that return a boolean indicating if the invoker method (this is, the method that invokes the "query method") has been already invoked before.
How to check that : just peeking at the stack trace and see if the method we want to check figures two or more times in the stack trace.
Having explaining that, here is the implementation of a method and the respective use of it.
This is not correct...
public class Test
{
public static boolean isRecusivelyInvoqued () {
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
boolean res = false;
// the first belong to "getStackTrace" and the second to "isRecusivelyInvoqued" (this method)
if (traces.length > 2) {
String invokedMethodName = traces[2].getMethodName(); // the third is the method we want to check
for (int i = 3; i < traces.length && !res; i++)
{
res = invokedMethodName.equals(traces[i].getMethodName());
i++;
}
}
return res;
}
// this is a recursive method, used to verify the correct functioning
public static int factorial (int n) {
System.out.println(isRecusivelyInvoqued());
if (n == 0) {
return 1;
}
else {
return n * factorial(n-1);
}
}
public static void main(String[] args)
{
System.out.println(factorial(4));
}
}
I realize if a method in differents namespaces (Class or instance) has the same name, it will return that is invoquedRecursively. I thing that one solution we got this far is that is correct ;) jeje.
This is working for me... is there a better way to archive my goal? How to determine when the current executing method is invoked recursively?