在使用Java局部内部类或者匿名内部类时,若该类调用了所在方法的局部变量,则该局部变量必须使用final关键字来修饰,否则将会出现编译错误“Cannot refer to a non-final variable * inside an inner class defined in a different method”
例如:
public void commRequest(Context ctx, String apiUri, HashMap<String, String> pairs,
final ApiCallback callback) {
HttpCallParam params = new HttpCallParam();
params.setUri(apiUri);
params.setPairs(pairs);
System.out.println("-apiUri---"+params.getUri());
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
System.out.println("-msg.arg1---"+msg.arg1);
if (msg.arg1 == HttpRequestService.MSG_ARG1_OK) {
if (msg.arg2 == HttpRequestService.MSG_ARG2_STR) {
callback.onError(msg.arg1, (String) msg.obj);
//如果callback不是final定义,就会报错
} else {
JSONObject json = (JSONObject) msg.obj;
String emsg = json.getString("errorMessage");
int ecode = json.getIntValue("errorCode");
callback.onSuccess(json, ecode, emsg);
}
} else {
if (BuildConfig.DEBUG) {Log.v("LX", "请求失败,可能网络不畅");}
callback.onError(msg.arg1, "请求失败,可能网络不畅");
}
return true;
}
});
request(ctx, params, handler);
}