从回调中返回字符串 - Java

2022-01-19 00:00:00 string return callback java

有谁知道我可以如何解决以下问题.我想从回调中返回一个字符串,但由于 final.

does anyone know how I can solve the following problem. I want to return a String from a callback, but I get only "The final local variable s cannot be assigned, since it is defined in an enclosing type", because of final.

 public String getConstraint(int indexFdg) {
    final String s;
    AsyncCallback<String> callback = new AsyncCallback<String>() {
        public void onFailure(Throwable caught) {
            caught.printStackTrace();
        }

        public void onSuccess(String result) {
            s = result;
        }
    };
    SpeicherService.Util.getInstance().getConstraint(indexFdg, callback);
    return s;
    }

推荐答案

异步回调的重点是通知你异步发生的事情,在未来的某个时间.如果要在方法完成运行后设置,则不能从 getConstraint 返回 s.

The whole point of an asynchronous callback is to notify you of something that happens asynchronously, at some time in the future. You can't return s from getConstraint if it's going to be set after the method has finished running.

在处理异步回调时,您必须重新考虑程序的流程.不是 getConstraint 返回一个值,而是应该作为回调的结果调用将继续使用该值的代码.

When dealing with asynchronous callbacks you have to rethink the flow of your program. Instead of getConstraint returning a value, the code that would go on to use that value should be called as a result of the callback.

作为一个简单(不完整)的示例,您需要更改以下内容:

As a simple (incomplete) example, you would need to change this:

 String s = getConstraint();
 someGuiLabel.setText(s);

变成这样:

 myCallback = new AsyncCallback<String>() {
     public void onSuccess(String result) {
         someGuiLabel.setText(result);
     }
 }
 fetchConstraintAsynchronously(myCallback);

编辑

一个流行的替代方案是未来的概念.未来是一个你可以立即返回的对象,但它只会在未来的某个时刻有一个值.这是一个容器,您只需要在请求时等待值.

Edit

A popular alternative is the concept of a future. A future is an object that you can return immediately but which will only have a value at some point in the future. It's a container where you only need to wait for the value at the point of asking for it.

您可以将持有未来视为持有您正在干洗的西装的门票.你马上拿到票,可以把它放在你的钱包里,把它送给朋友……但是一旦你需要把它换成真正的西装,你需要等到西装准备好.

You can think of holding a future as holding a ticket for your suit that is at the dry cleaning. You get the ticket immediately, can keep it in your wallet, give it to a friend... but as soon as you need to exchange it for the actual suit you need to wait until the suit is ready.

Java 有这样一个类(Future<V>) 被 ExecutorService API.

Java has such a class (Future<V>) that is used widely by the ExecutorService API.

相关文章