java - 为最终变量赋值

标签 java callback final

假设我有这段代码:

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/

相关文章:

java - 在for循环中动态选择变量

java - 使用 REST 请求表中记录数的最佳方法

java - SIP 服务器中的身份验证问题

java - 如何将驻留在 Amazon ec2 实例中的 Tomcat 7 server.xml 文档库指向 Amazon S3 存储桶中的文件夹

c# - 回调函数

javascript - 当一个同步函数突然需要一个异步值时,避免链式重构?

javascript - react native Swift 回调

java - 序列化和不可变对象(immutable对象)

java - Android : final local variable vs local variable 中的性能或优化

java - 当我尝试使用 .getText() 时,JTextField 想成为最终结果