假设我有这段代码:
public HttpResponse myFunction(...) {
final HttpResponse resp;
OnResponseCallback myCallback = new OnResponseCallback() {
public void onResponseReceived(HttpResponse response) {
resp = response;
}
};
// launch operation, result will be returned to myCallback.onResponseReceived()
// wait on a CountDownLatch until operation is finished
return resp;
}
显然我不能从 onResponseReceived 给 resp 赋值,因为它是一个最终变量,但如果它不是最终变量,onResponseReceived 就看不到它。 那么,如何从 onResponseReceived 中为 resp 赋值呢?
我的想法是创建一个包装类来封装resp对象。最终对象将是这个包装类的一个实例,我可以将值分配给在最终类(不是最终类)中处理对象的 resp。
代码应该是这样的:
class ResponseWrapper {
HttpResponse resp = null;
}
public HttpResponse myFunction(...) {
final ResponseWrapper respWrap = new ResponseWrapper();
OnResponseCallback myCallback = new OnResponseCallback() {
public void onResponseReceived(HttpResponse response) {
respWrap.resp = response;
}
};
// launch operation, result will be returned to myCallback.onResponseReceived()
// wait on a CountDownLatch until operation is finished
return respWrap.resp;
}
您如何看待这个解决方案?
最佳答案
java.util.concurrent.atomic.AtomicReference
标准做法是使用最终的 AtomicReference,您可以设置和获取它。这也增加了线程安全的好处 :) 正如您提到的,CountDownLatch 有助于等待完成。
关于java - 为最终变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13845174/