Login with  Log in with facebook
Hiring Manager? SIGN UP HERE
1

How do we find the level of recursion from a recursive method.

ie. How do we know the invocation level for a rwcursive method.

if it is invoked first, the level is one, when it is invoked recursively for second time

from within itself, the recursion level is 2 and so on.

 

Pravin Jain
01/26/2012 at 05:21
1 Answer
1
1

We could develop a method as follows

public static final int getRecursionLevel() {

        StackTraceElement[] stackElements = Thread.currentThread().getStackTrace();
        String invokingClassName = stackElements[2].getClassName();
        String invokingMethodName = stackElements[2].getMethodName();
        int level = 1;
        for (level = 1; level < stackElements.length-1; level++) {
            if (!((stackElements[level+1].getClassName().equals(invokingClassName)) && (stackElements[level+1].getMethodName().equals(invokingMethodName)))) {
                level--;
                break;
            }
        }
        return level;
}

 

Pravin Jain
01/26/2012 at 05:46

If you want to post any answer to this forum then you need to log in.
Schedule a Demo

Schedule a Demo with us

Name *
Email *
Phone *
Company *
Details