java - 检查方法是否被递归调用的正确方法

标签 java recursion

重要提示:示例是错误的,我在底部解释了原因

正如标题所述,问题是要定义一种方法来确定何时以递归方式调用当前执行方法。

我考虑过有一个“查询方法”,它返回一个 boolean 值,指示调用者方法(即调用“查询方法”的方法)之前是否已经被调用过。

如何检查:只需查看堆栈跟踪,看看我们想要检查的方法是否数字两次或更多次 堆栈跟踪

解释完之后,这里是一个方法的实现以及它的各自的使用。

这是不正确的...

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));
    }

}

我意识到如果不同命名空间(类或实例)中的方法具有相同的名称,它将返回递归调用的方法。我认为到目前为止我们得到的一个解决方案是正确的;)jeje。

这对我有用...有更好的方法来实现我的目标吗?如何判断当前执行的方法何时被递归调用?

最佳答案

这样怎么样:您的方法将一个 boolean 值传递给递归方法的下一个调用,告诉它已被递归调用:

public static int factorial (int n) {
    return privateFactorial(n, false);
}

private static int privatefactorial(int n, boolean calledRecursively) {
    System.out.println(calledRecursively);
    if (n == 0) {
        return 1;
    }
    else {
        return n * privateFactorial(n-1, true);  // tell next invocation here!
    }
}

关于java - 检查方法是否被递归调用的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17886434/

相关文章:

java - 在库中管理 ExecutorService 的最佳实践是什么?

java - 为什么我的 Java 类可以在不使用 "this."的情况下工作?

java - 两种形式但只有1个jsp文件

java.lang.OutOfMemoryError : Java heap space for java 8 错误

c - 从动态规划函数中获取值

javascript - 递归查找范围内加起来等于目标值的 n 个数字

java - 强制子类重写这两个方法或一个都不重写

java - Apache Pivot 桌面应用程序中的菜单栏不可见

c++ - 具有指针 C 成员的类 C 的析构函数

java - 使用词边界和 POS 将句子拆分为固定大小的 block