我有一个必须返回布尔值的方法。该方法具有异步调用以运行方法。在运行方法中,我必须在封闭方法中设置变量。下面是我的代码。

private boolean isTrue() {
    boolean userAnswer;
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            userAnswer = MessageDialog.openQuestion(new Shell(), "some message", "some question?");
        }
    });
    return userAnswer;
}

这段代码给出了错误-“userAnswer”必须为final,如果我将其设置为final,则无法为其分配值。请提出一种处理这种情况的方法。

最佳答案

如果需要将java.util.concurrent.FutureTask<V>调整为Callable<V>,则可以使用Runnable

public class UserQuestion implements Callable<Boolean> {

    private String message;
    private String question;

    public UserQuestion(String message, String question) {
        this.message = message;
        this.question = question;
    }

    public Boolean call() throws Exception {
        boolean userAnswer = MessageDialog.openQuestion(new Shell(),
                message, question);
        return Boolean.valueOf(userAnswer);

    }
}

UserQuestion userQuestion = new UserQuestion("some message", "some question?");
FutureTask<Boolean> futureUserAnswer = new FutureTask<Boolean>(userQuestion);
Display.getDefault().asyncExec(futureUserAnswer);
Boolean userAnswer = futureUserAnswer.get();

09-11 17:50