如何从上一个故障点重新启动方法

时间:2012-10-18 15:44:16

标签: java

我有这样的方法:

    public void runMethod()
    {
    method1();
    method2();
    method3();
    }

我想根据id多次调用此runMethod。但是,如果说method2()由于某种原因失败了,那么当我调用runMethod时,它应该执行method3()而不是再次尝试执行method1()(已经成功运行了这个id)。

实现这一目标的最佳方式是什么?

非常感谢您的帮助

3 个答案:

答案 0 :(得分:3)

您可以在地图中记录方法是否已成功执行。

private Map<String, Boolean> executes = new HashMap<String, Boolean>();

public void method1() {
    Boolean hasExecuted = executes.get("method1");
    if (hasExecuted != null && hasExecuted) {
        return;
    }
    executes.put("method1", true);
    ...
}

// and so forth, with method2, method3, etc

答案 1 :(得分:1)

您正在寻找某种状态机。将方法执行的状态保持在数据结构中(例如,地图)。

在方法开始时,您需要检查给定id的method1的执行是否成功执行。

public void runMethod()
{
  method1();
  method2()
  method3();
}
private Set<Integer> method1Executed = new HashSet<Integer>();
private Set<Integer> method2Executed = new HashSet<Integer>();

private void method1(Integer id)
{
    if (method1Executed.contains(id)) {
        return;
    }
    // Processing. 
    method1Executed.add(id)
}

 // Similar code for method2.

答案 2 :(得分:1)

我的解决方案是添加一个int是一个指标,而不是引入地图,特别是如果经常调用代码。 它看起来像这样:

public int runMethod(int flag) {
    if (flag < 1) {
        method1();
        if (method1failed) {
            return 1;
        }
    }
    if (flag < 2) {
        method2();
        if (method2failed) {
            return 2;
        }
    }
    if (flag < 3) {
        method3();
        if (method3failed) {
            return 3;
        }
    }
    return 4;
}