is it possible to store method name in an array, and count how many times it has been called?

James Wong :

I need to simulate a call stack. Now I've already implemented my stack, now I'm wondering if there's a way to store the method name in the array.

For instance, I have a recursion function that loops 5 times, so the stack will be:

recur() //fifth 
recur() //fourth
recur() //third
recur() //second
recur() //first

but is there anyway to store them into an array and display it out? I don't have to care about what it does inside the recursion function, I just want to display out the name of the stack and the sequence and how it works.

Ezequiel :

You could count the number of invocations without passing any new parameter to the recur method.

recursiveMethodCount filters the current stack trace and counts the ocurrences.

import java.util.Arrays;

public class StackTrace {

    public static void main(String[] args) {
        recur();
    }

    public static void recur() {
        long recursionLevel = recursiveMethodCount("StackTrace", "recur");
        if (recursionLevel < 10) {
            System.out.println(String.format("Recursion level is %d, invoking recur() again.", recursionLevel));
            recur();
        } else {
            System.out.println(String.format("Recursion level is %d, no more invocations.", recursionLevel));
        }
        System.out.println(String.format("Recursion level is %d, returning.", recursionLevel));
    }

    public static long recursiveMethodCount(String declaringClass, String methodName) {
        return Arrays.stream(Thread.currentThread().getStackTrace())
                .filter(stackTraceElement -> stackTraceElement.getClassName().equals(declaringClass))
                .filter(stackTraceElement -> stackTraceElement.getMethodName().equals(methodName))
                .count();

    }
}

The output of this code is

Recursion level is 1, invoking recur() again.
Recursion level is 2, invoking recur() again.
Recursion level is 3, invoking recur() again.
Recursion level is 4, invoking recur() again.
Recursion level is 5, invoking recur() again.
Recursion level is 6, invoking recur() again.
Recursion level is 7, invoking recur() again.
Recursion level is 8, invoking recur() again.
Recursion level is 9, invoking recur() again.
Recursion level is 10, no more invocations.
Recursion level is 10, returning.
Recursion level is 9, returning.
Recursion level is 8, returning.
Recursion level is 7, returning.
Recursion level is 6, returning.
Recursion level is 5, returning.
Recursion level is 4, returning.
Recursion level is 3, returning.
Recursion level is 2, returning.
Recursion level is 1, returning.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334547&siteId=1
Recommended