簡體   English   中英

Java在兩個類之間傳遞數據

[英]Java passing data between two classes

我有一個非常愚蠢的基本問題,但是我似乎無法解決。 我試圖在3個類之間傳遞數據,所以這是我采用的方法:

A級

public class GroupChat {

    public String message;
    public String myId;
    public String otherID;

    public GroupChat() {

    }

    public String getOtherID() {
        return otherID;
    }

    public void setOtherID(String otherID) {
        this.otherID = otherID;
    }

    public String getMyId() {
        return myId;
    }

    public void setMyId(String myId) {
        this.myId = myId;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

B類-單擊按鈕即可生成數據

GroupChat chat = new GroupChat();
chat.setParticipants(participants);
chat.setMyId(userId);
chat.setOtherID(id);
chat.setMessage(message);

當我在GroupChat類中打印這些變量的日志時,一切都很完美。

但是,當我嘗試使用getter將數據獲取到C類(這是我需要的地方)時,它們將返回null值。

C級

GroupChat chat = new GroupChat();
chat.getMessage(),
chat.getItemView(),
chat.getMyId(),
chat.getOtherID());

我什至嘗試將數據記錄在GroupChat類中。 當我使用setter輸入數據時,一切都很好,但是在getter上記錄數據時,這些返回null。 GroupChat類中必須有某些東西可以使變量無效。

有人可以指出我正確的方向嗎? 太感謝了。

每次致電:

GroupChat chat = new GroupChat();

您正在使用默認值(例如0,null)創建新對象。

如果要使用對象“ B”,則必須從調用設置器的函數中將其返回。

例如

public GroupChat getDataAfterButtonPress() {
    GroupChat chat = new GroupChat();
    chat.setParticipants(participants);
    chat.setMyId(userId);
    chat.setOtherID(id);
    chat.setMessage(message);
    return chat;
}

然后,您可以稍后在代碼中使用此對象:

GroupChat result = getDataAfterButtonPress();

沒有完整的代碼很難下結論。 我能看到的唯一問題是,兩種情況下都使用不同的實例。 在C類中,您將創建一個新的GroupChat,而不是傳遞在B類中創建的GroupChat。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM