如何检测Java方法中的递归

Ste*_* Oh 1 java recursion

如何从方法体内部检查,如果我调用的方法,则依次调用我的方法.

// the method, that I control
public void myMethod() {
     if( stackContainsMyMethod() ) {
        throw new RuntimeException("do not call me");
     } 
     ...
     handler();
}

// someone else implements this
protected abstract void handler();
Run Code Online (Sandbox Code Playgroud)

处理程序不能调用myMethod().我想在运行时强制执行此操作.任何人都可以帮助一个简单的方法?

问候.

Pea*_*oto 6

如果您尝试仅在第二轮检测它,则会更容易.这样的事情应该有效.

boolean isRunning;

public void myMethod() {
    if (isRunning) {
        throw new RuntimeException("do not call me");
    }
    isRunning=true;
    handler();
    isRunning=false;
}
Run Code Online (Sandbox Code Playgroud)