回调方法中的变量范围在每个内部调用

时间:2015-09-14 15:03:39

标签: java

在下面的代码块中,我是否会在异步帖子中的被叫URL响应中获得正确的链接值?

for (Link link:links){
       client.post(link.url, params, new AsyncHttpResponseHandler() { //async
       @Override
       public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
           Log.d("test","Success Post - "+link.url);
       }

       @Override
       public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
           Log.d("test","Failed Post"+link.url);
       }
    })      
}

2 个答案:

答案 0 :(得分:2)

您的匿名类实例将捕获link变量在创建时的值。因此,您将检索正确的值。

特别注意增强关于迭代变量的语义:它是有效的最终,与基于索引的迭代习语中的int i不同。在这两种情况下,变量的范围略有不同:i的范围是整个for循环,link变量的范围只是循环体。这在语法上并不明显,因为在这两种情况下,变量都在for-loop头中声明。

答案 1 :(得分:0)

Not necessarily. Consider the case when there is a parallel thread running and changing the values of url fields of in your Link instances.

Even though the anonymous class captures a correct reference to the Link object contained by link variable, if url field is changed at any of the objects before response comes back, you'll get the changed value.

So it also depends on your application design. If there is no such thread, you're safe.