gpt4 book ai didi

java - 为最终变量赋值

转载 作者:行者123 更新时间:2023-11-29 09:44:34 25 4
gpt4 key购买 nike

假设我有这段代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com