我使用“令牌”(声明为final的ValueContainer类的实例)来保存从JSON请求接收的数据。在匿名函数Response.Listener()中,我设置了令牌的值,并且它可以工作。

Log.d("myTag", "token value1:" + token.getValue());


该行显示正确的值(非null)。但是,当我再次检查token.getValue()的值时(这次在匿名函数之外)

Log.d("myTag", "token value2:" + token.getValue());


我得到token.getValue()= null。我不明白为什么令牌的值似乎重置为null。我想念什么吗?

完整代码:

public class MainActivity extends AppCompatActivity {

class ValueContainer<T> {
    private T value;

    public ValueContainer() { }

    public ValueContainer(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final ValueContainer<String> token = new ValueContainer<String>();
    String getTokenUrl = "http://www.someurl.com/?somekey=somevalue";

    JsonObjectRequest getTokenRequest = new JsonObjectRequest(
            Request.Method.GET, getTokenUrl, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                token.setValue(response.getString("token"));
                Log.d("myTag", "token value1:" + token.getValue());

                mainTextView.append("Response: JsonObjectRequest successful: get_token: " + token.getValue() + "\n");
            } catch (JSONException e) {
                mainTextView.append("Response: JSONException: getString():" + e);
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            mainTextView.append("Response: JsonObjectRequest failed: " + error + "\n");
        }
    });
    Log.d("myTag", "token value2:" + token.getValue());
}

最佳答案

您可以更改“最终”对象的“实际内容”,但不能更改其地址,如示例所示。

 String stringTest = "test String";

 StringBuffer normalTest = new StringBuffer(stringTest);
 normalTest = normalTest.append(" end");
 normalTest.delete(0, 5);
 System.out.println(normalTest);

 final StringBuffer finalTest = new StringBuffer(stringTest);
// finalTest = finalTest.append(" end"); // can't work;
 finalTest.delete(0, 5);
 System.out.println(finalTest);


您可以通过您的代码进行测试

//token =  new Token("...")// can't work
token.changeTheToken("...")// work ok

关于java - 为什么即使在匿名函数中更改了声明为final的对象的状态,似乎也要重置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35715859/

10-16 06:28