私がこのコードを持っているとしましょう:
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;
}
このソリューションについてどう思いますか?