ph0*_*h09 9 java string return callback
有谁知道如何解决以下问题.我想从回调中返回一个String,但我只得到"最终的局部变量s不能被分配,因为它是在一个封闭的类型中定义的",因为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;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 15
异步回调的重点是通知您在将来的某个时间异步发生的事情.你不能返回s
从getConstraint
它是否会被设定后的方法已经结束.
处理异步回调时,您必须重新考虑程序的流程.而不是getConstraint
返回值,将继续使用该值的代码作为回调的结果.
作为一个简单(不完整)的例子,你需要改变这个:
String s = getConstraint();
someGuiLabel.setText(s);
Run Code Online (Sandbox Code Playgroud)
进入这样的事情:
myCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
someGuiLabel.setText(result);
}
}
fetchConstraintAsynchronously(myCallback);
Run Code Online (Sandbox Code Playgroud)
一种流行的替代方案是未来的概念.未来是一个对象,您可以立即返回,但在将来的某个时刻只会有一个值.它是一个容器,您只需要在要求它时等待值.
您可以考虑为持有干洗衣服的机票持有未来.你立刻得到了票,可以把它放在你的钱包里,交给朋友......但是一旦你需要交换实际的套装,你需要等到套装准备就绪.
Java有这样一个class(Future<V>
),它被ExecutorService API广泛使用.
小智 5
另一种解决方法是定义一个新类,称为 SyncResult
public class SyncResult {
private static final long TIMEOUT = 20000L;
private String result;
public String getResult() {
long startTimeMillis = System.currentTimeMillis();
while (result == null && System.currentTimeMillis() - startTimeMillis < TIMEOUT) {
synchronized (this) {
try {
wait(TIMEOUT);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}
public void setResult(String result) {
this.result = result;
synchronized (this) {
notify();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将您的代码更改为此
public String getConstraint(int indexFdg) {
final SyncResult syncResult = new SyncResult();
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
public void onSuccess(String result) {
syncResult.setResult(result);
}
};
SpeicherService.Util.getInstance().getConstraint(indexFdg, callback);
return syncResult.getResult();
}
Run Code Online (Sandbox Code Playgroud)
该getResult()
方法将被阻塞,直到setResult(String)
方法被调用或TIMEOUT
到达。