如何将一个 class 中的值设置为变量并从另一个 class 中获取该变量的值?

How to set a value into a variable from one class and get that variable's value from other class?

我想将数据设置到一个 class 的变量中,并想在另一个 class 中获取该变量的数据。

我测试了一个例子。但我得到的是空值。

示例 class Data:

public class Data {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

MainActivityclass我做的是:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Data data = new Data();
        data.setText("HELLO");
        System.out.println("GET from Main class: " + data.getText());

        // Call the get class method
        Test test = new Test();
        test.execute();
    }

测试class:

public class Test {

    public void execute() {

        Data data = new Data();
        System.out.println(" GET from Test class: " + data.getText());

    }

}

输出:

I/System.out: GET from Main class: HELLO
I/System.out:  GET from Test class: null

如何访问主要 class 获取?

谢谢。

它是空的,因为你从数据中创建了新对象!!!如果您想从数据中获取价值,您必须将数据对象传递给您的测试方法。

需要说明的是data变量是静态变量,也就是说对于Data的所有实例都是一样的。完成后,您就不需要数据实例了。

public class Data {
    private static String sText;

    public static String getText() {
        return sText;
    }

    public static void setText(String text) {
        sText = text;
    }
}

然后你静态调用数据。 Data.getText() 和 Data.setText("hello")

编辑: 但正如 Stultuske 所写,您应该温习一下基础知识。我的 "solution" 会修复您的测试,但这不是一个好的测试,因为一旦您开始处理大型应用程序,将所有内容都设为全局会导致一团糟。

目前的做法,execute() 无法知道对象的值,因为它是一个新对象。您有两个解决方案:

  • 您可以将 text 变量放在 static 中:这样,该值将由所有实例共享。任何 Data 对象都可以更改 text 的值,并且您可以在不创建实例的情况下更改变量。

  • 你也可以在execute()函数的参数中传递Data对象。这样,您创建的每个 Data 对象都会有自己的 text 变量。