2017-07-01 47 views
-1

我的Get和Set返回null。
我覺得它在我的Set方法中缺少一些東西。獲取並設置返回Null

我Authen.java:

public class Authen { 
    String sessionID; 

    public void setSessionID(String sessionID) { 
     this.sessionID = sessionID; 
    } 

    public String getSessionID(){ 
     return this.sessionID; 
    } 
} 

我的設置方法:

 String id="1234"; 
     Authen at = new Authen(); 
     at.setSessionID(id); 

當我登錄SID

Authen at = new Authen(); 
String sID = at.getSessionID(); 
+3

你最後的代碼片段總是返回'null',因爲你讓自己成爲一個新的'Authen'對象,然後嘗試從未設置時檢索會話ID。 –

+0

setter不返回任何東西 –

+0

類的構造函數在哪裏? –

回答

0

你重新聲明at我get方法返回null,其去除你設定的任何值。

後您設置id,不創建一個新的Authen對象

所以更改此設置:

String id="1234"; 
Authen at = new Authen(); 
at.setSessionID(id); 

Authen at = new Authen(); // This is where you create a new EMPTY authen 
String sID = at.getSessionID(); 

到:

String id="1234"; 
Authen at = new Authen(); 
at.setSessionID(id); 

String sID = at.getSessionID(); 
+0

如果將A.class上的setSessionID設置爲authen.java 我想從authen.java上獲取B.class上的SessionID 我該如何執行此方法? –

+0

@metalwake你不能。 – wedo

+0

你不能,除非你使Authen成爲一個單身人士,但是你不能爲A和B擁有不同的ID – Parker

0

你應該像下面使用.. 。

String id="1234"; 
Authen at = new Authen(); 
at.setSessionID(id); 
String sID = at.getSessionID(); 

不需要更新。

0

你的sID爲空的原因是你'新'一個全新的對象,因爲你在第二次聲明'at'對象Authen at = new Authen();
如果您想正確獲取sID,則不需要再次啓動Authen。 只是做:

String id="1234"; 
Authen at = new Authen(); 
at.setSessionID(id); 
String sID = at.getSessionID(); 
0

您可以從A類,如果需要有它轉移認證介紹實例B(假設類A創建B的實例):

class A { 
    private void aMethod() { 
     String id="1234"; 
     Authen at = new Authen(); 
     at.setSessionID(id); 
     ... 
     B b = new B(at); 
    } 
} 

class B { 
    private Authen authen; 

    public B(Authen at) { 
     this.authen = at; 
     ... 
    } 

    private void anotherMethod() { 
     String sID = this.authen.getSessionID(); 
     ... 
    } 
} 

顯然這個代碼不完整,只是爲了展示主要想法 - 只是衆多可能性中的一種。