我怎样才能得到已经在另一个 class 中设置的实例值?

How can I get a value of instance which is already set in another class?

我是 Java 的新手。我有 3 个 classes: 1-DataHolder 2-SetToDateHolder 3-GetFromDataHolder;在“SetToDateHolder”class 中,我将值设置为 dataholder 对象,我试图在“GetFromDataHolder”class 中访问它,但它得到了空值,我知道这是因为新实例创建。你能帮我意识到我可以获得我在另一个 class.

中设置的实例的值吗

这些是 classes:

public class DataHolder {

    private String myName;

    public String getMyName() {
        return myName;
    }

    public void setMyName(String myName) {
        this.myName = myName;
    }
}

public class SetToDataHolder {

    public static void main(String[] args) {
        DataHolder dataHolder = new DataHolder();
        dataHolder.setMyName("Wesley");
    }

}

public class GetFromDataHolder{
    
    public static void main(String[] args) {
        DataHolder dataHolder = new DataHolder();
        System.out.println(dataHolder.getMyName());
    }

}

我真的不明白为什么你需要 2 个额外的 classes,因为你的 DataHolder class 中已经有了 getter / setter,但方法如下你应该能够继续你的逻辑:

public class DataHolder {

    private String myName;

    public String getMyName() {
        return myName;
    }

    public void setMyName(String myName) {
        this.myName = myName;
    }
}

public class SetToDataHolder {
    
    private DataHolder dataHolder;

    public SetToDataHolder(DataHolder dataHolder){
        this.dataHolder = dataHolder;
    }

    public void setMyName(String myName) {
        this.dataHolder.setMyName(myName);
    }
}

public class GetFromDataHolder{
    
    private DataHolder dataHolder;

    public GetFromDataHolder(DataHolder dataHolder){
        this.dataHolder = dataHolder;
    }

    public String getMyName() {
        this.dataHolder.getMyName();
    }
}

public class MainClass{
    
    public static void main(String[] args){
        DataHolder dataHolder = new DataHolder();

        SetToDataHolder setToDataHolder = new SetToDataHolder(dataHolder);
        setToDataHolder.setMyName("Wesley");

        GetFromDataHolder getFromDataHolder = new GetFromDataHolder(dataHolder);
        System.out.println(getFromDataHolder.getMyName());
    }
}

想法是您的 SetToDataHolder 和 GetFromDataHolder 可以访问同一个 DataHolder 实例。