如何在整个 class 中使用内部 class 变量
How to use inner class variable in whole class
我有一个类似这样的方法来使用 loopj 从网络服务中获取名字。
private void getfirstName() {
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Accept", "application/json"));
RestClient.getShiftCodes(MainActivity.this, "RestService/First_Name", headers.toArray(new Header[headers.size()]),
null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<String> firstNameArray = new ArrayList<String>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject c = response.getJSONObject(i);
String first_NameArray = c.getString("firstName");
firstNameArray.add(first_NameArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
String first_Name= firstNameArray.get(0);
}
});
}
如果我想在其他方法中使用 first_name 字符串值,我会收到此错误
Cannot refer to a non-final variable first_name inside an inner class defined in a different method
即使我把它改成final我也不能用。怎么才能全class.
您无法直接获取内部 class 变量的引用,而是在外部 class 中声明并在内部 class 中赋值。然后您可以从任何 classes.
访问变量
String first_Name
声明的外部函数
我有一个类似这样的方法来使用 loopj 从网络服务中获取名字。
private void getfirstName() {
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Accept", "application/json"));
RestClient.getShiftCodes(MainActivity.this, "RestService/First_Name", headers.toArray(new Header[headers.size()]),
null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<String> firstNameArray = new ArrayList<String>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject c = response.getJSONObject(i);
String first_NameArray = c.getString("firstName");
firstNameArray.add(first_NameArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
String first_Name= firstNameArray.get(0);
}
});
}
如果我想在其他方法中使用 first_name 字符串值,我会收到此错误
Cannot refer to a non-final variable first_name inside an inner class defined in a different method
即使我把它改成final我也不能用。怎么才能全class.
您无法直接获取内部 class 变量的引用,而是在外部 class 中声明并在内部 class 中赋值。然后您可以从任何 classes.
访问变量String first_Name
声明的外部函数