-1
我得到一個訪問令牌作爲響應,並嘗試將它保存在類變量中。但是當我從一個getter訪問變量時,我得到空指針異常。這是代碼片段。 我不完全明白這個原因,因爲我將局部變量的值分配給類變量。所以即使變量是私有的,我也應該可以通過類的任何成員方法來訪問它。將局部變量的值傳遞給類變量時,在java中訪問類變量時會給出NullPointer
public class Login {
private String access_token;
public String doLogin(String uName) throws Exception {
BaseClass bc = new BaseClass();
String loginUrl = "http://www.example.com/login";
bc.setUrl(loginUrl);
bc.REQUEST_METHOD="POST";
bc.CONTENT_TYPE="application/json";
//System.out.println(url);
System.out.println(bc.getUrl());
bc.openConnection();
bc.con.setDoOutput(true);
JSONObject loginRequest = new JSONObject();
loginRequest.put("userName", uName);
loginRequest.put("password", "password");
System.out.println(loginRequest);
DataOutputStream dos = new DataOutputStream(bc.con.getOutputStream());
dos.writeBytes(loginRequest.toString());
dos.flush();
dos.close();
int responseCode = bc.con.getResponseCode();
System.out.println(responseCode);
BufferedReader login = new BufferedReader(new InputStreamReader(bc.con.getInputStream()));
String inputLine;
StringBuffer loginResponse = new StringBuffer();
while((inputLine=login.readLine())!=null){
loginResponse.append(inputLine);
}
login.close();
System.out.println("#####BEGIN LOGIN RESPONSE#####");
System.out.println(loginResponse.toString());
//setAccess_token(access_token);
JSONObject jobj= new JSONObject(loginResponse.toString());
JSONArray jArray = jobj.getJSONArray("respList");
String access_token = jArray.getJSONObject(0).getString("ticket");
token = jArray.toString();
//access = new JSONObject(response);
System.out.println("printing token"+token);
access_token = token;
System.out.println("printint access token"+access_token);
return access_token;
}
public String getToken(){
System.out.println("printing return token"+access_token);// I GET NULL POINTER EXCEPTION HERE
return access_token;
}
看看_variable shadowing_。 – 2014-09-12 18:26:41
「代碼牆」 - 該方法做得太多。我會把它變成幾種可以獨立測試的方法。 – duffymo 2014-09-12 18:28:14