【发布时间】:2018-12-05 23:06:23
【问题描述】:
我的问题是当作为参数传递给异步回调时我们应该如何使用匿名类? 例如,如果我有以下代码:
interface MyListener {
void onSucces(String requestedAction, JSONObject response);
void onError(String requestedAction, JSONObject response, int statusCode);
};
interface CallbackInterface {
void onResponse(String requestedAction, JSONObject response, int statusCode);
};
void doAsyncJob(String action, CallbackInterface callbackItf);
void makeJob(String action, final MyListener listener) {
doAsyncJob(action, new CallbackInterface {
void onResponse(String requestedAction, JSONObject response, int statusCode) {
if (statusCode == 200) {
listener.onSucces(requestedAction, response);
} else {
listener.onError(requestedAction, response, statusCose);
}
}
});
}
for(i = 1; i < 1000; i++) {
makeJob("Action_" + i, new MyListener{
void onSucces(String requestedAction, JSONObject response) {
//process response
}
void onError(String requestedAction, JSONObject response, int statusCode) {
//process error
});
}
通过每次分配新的侦听器 (MyListener) 在循环中调用“makeJob”,稍后由 “onResponse”,这个监听器有资格成为垃圾收集器吗? 是否需要保留一个对该侦听器的引用,以确保稍后在“onResponse”中使用时不会被丢弃?
【问题讨论】:
标签: java garbage-collection final anonymous-class