假设我有这个代码:
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 对象。最终对象将是这个包装类的一个实例,我可以将值分配给在最终类(不是最终的)内的对象上工作。
代码将是这个:
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;
}
您如何看待这个解决方案?