使用在SWF TryCatch中的doCatch()方法中的doTry()方法中定义的变量

时间:2015-12-29 22:02:08

标签: java asynchronous amazon-swf

我有一个SWF TryCatch类结构,如:

new TryCatch() {
        @Override
        protected void doTry() throws Throwable {
            Promise<Boolean> ifHostsWereReserved = client.reserveHostsForOnboarding());
            Promise<Boolean> ifHostsReleaseCompleted = client.releaseExtraHostsAfterOnboarding();
        }

        @Override
        protected void doCatch(Throwable e) throws Throwable {
            updateAvailableHosts(ifHostsWereReserved,
            ifHostsReleaseCompleted);
        }
}

我无法访问doCatch()块中的变量,因为变量是doTry()方法的本地变量。另外,如果我在doTry()方法之前声明它们并在doTry()方法中更新它们的值,它们就不再等同于final,我收到了编译错误。

什么是处理这个问题的首选方法。

2 个答案:

答案 0 :(得分:1)

你可以声明这样的变量:

new TryCatch() {
        Promise<Boolean> ifHostsWereReserved;
        Promise<Boolean> ifHostsReleaseCompleted;

        @Override
        protected void doTry() throws Throwable {
            ifHostsWereReserved = client.reserveHostsForOnboarding());
            ifHostsReleaseCompleted = client.releaseExtraHostsAfterOnboarding();
        }

        @Override
        protected void doCatch(Throwable e) throws Throwable {
            updateAvailableHosts(ifHostsWereReserved,
            ifHostsReleaseCompleted);
        }
}

答案 1 :(得分:1)

eazimmerman评论是正确的。如果需要在TryCatch之外引用变量,可以像这样使用Settable:

final Settable<Boolean> ifHostsWereReserved = new Settable<>();
final Settable<Boolean> ifHostsReleaseCompleted = new Settable<>();

new TryCatch() {

    @Override
    protected void doTry() throws Throwable {
        ifHostsWereReserved.chain(client.reserveHostsForOnboarding()));
        ifHostsReleaseCompleted.chain(client.releaseExtraHostsAfterOnboarding());
    }

    @Override
    protected void doCatch(Throwable e) throws Throwable {
        updateAvailableHosts(ifHostsWereReserved,
        ifHostsReleaseCompleted);
    }
};

useTheseVariables(ifHostsWereReserved, ifHostsReleaseCompleted);