为最终变量赋值

Mas*_*imo 1 java final callback

假设我有这个代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

显然我无法从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;
}
Run Code Online (Sandbox Code Playgroud)

您对此解决方案有何看法?

mba*_*ows 7

java.util.concurrent.atomic.AtomicReference中

标准做法是使用最终的AtomicReference,您可以设置和获取.这也增加了线程安全的好处:)正如您所提到的,CountDownLatch有助于等待完成.