重要提示:示例是错误的,我在底部解释了原因
正如标题所述,问题是要定义一种方法来确定何时以递归方式调用当前执行方法。
我考虑过有一个“查询方法”,它返回一个 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/