通过多次递归调用持久化信息

persisting information through multiple recursive calls

我正在扩展第 3 方 class 并重写我制作的方法 "recursive",如下所示:

public class SubFoo extends Foo {
    ....
    @Override
    public void bar(...) {
        recursiveSpecificSet.add(...);
        if(recursiveSpecificSet.contains(...)){ 
            ...
            methodCallThatCallsBar(...);
            ...
        }
    }
}

由于此方法被覆盖,我无法控制方法签名。我想通过 recursiveSpecificSet 将父递归调用的信息传递给它的子对象,但我希望该信息特定于该递归链。例如:

SubFoo sf = new SubFoo();
sf.methodCallThatCallsBar(...); // first call calls bar recursively 3 times
sf.methodCallThatCallsBar(...); // second call calls bar recursively 5 times

在上面的代码中,第一次调用的 recursiveSpecificSet 变量不应干扰第二次调用的 recursiveSpecificSet。

这可能吗?我知道您通常可以通过方法参数在递归迭代之间传递信息,但我无法控制方法签名。同一个线程也可以多次调用bar方法,所以一个线程局部变量就不行了。

如果我对你的问题理解正确,答案不是使 bar 递归,而是使 bar 调用递归的私有辅助方法。

@Override
public void bar() {
    helper(new HashSet<>());
}

private void helper(Set<String> recursiveSpecificSet) {
    ...
    helper(recursiveSpecificSet);
    ...
}

使用存储递归深度和负载数据的本地线程。如果在输入 bar() 时 threadlocal 为空,则用深度 1 初始化它,否则递增深度。离开 bar() 后,减少深度,如果它进入 1,则删除 threadlocal。您可能必须在 finally 中执行此操作,以免在抛出异常时中断。

public void bar() {
    if (threadLocal == null) {
        threadLocal.set(new Context(recursiveSpecificSet));
    }
    threadLocal.get().increaseDepth();

    try {
        ...
        methodCallThatCallsBar(...);
        ...
    }
    finally {
        threadLocal.get().decreaseDepth();
        if (threadLocal.get().isExitRecursion()) {
            threadLocal.remove();
        }
    }
}