使用类存储在Java中的静态数据?静态、数据、Java

2023-09-06 06:31:03 作者:灭狗离骚

这是个坏主意创建一个单独的类,并用它作为存储其中只包含静态数据变量?

Is it a bad idea creating a separate class and use it as a storage which consists only of static data variables?

我目前正在为Android开发的应用程序,但问题是,一般的Java。

I am currently developing an app for android, but the question is general for Java.

在Android的情况下,我很感动各种活动,我想储存一些全局/静态标志/可变因素在不同的阶层和能够从我想要的任何活动访问它们。

In case of android, I am moving across activities and I would like to store some global/static flags/varibles in that separate class and being able to access them from any activity I want.

PS。数据只用于会话所需时间

PS. The data is required only for the session time.

推荐答案

嗯,这不是一个坏主意。您可以使用这种类型的类中的Andr​​oid。但小幅盘整这里。相反,维持持有静态数据类的,可以作出这样的类来扩展应用程序类,并用它存储数据。

Well, that's not a bad idea. You can use such type of a class in Android. But a small correction here. Instead of maintaining a class that holds static Data, you can make that class to extend Application class and use it store the data.

下面是一个例子,

public class HelloApplication extends Application {
        private int globalVariable=1;

        public int getGlobalVariable() {
                return globalVariable;
        }

        public void setGlobalVariable(int globalVariable) {
                this.globalVariable = globalVariable;
        }
        @Override
        public void onCreate() {
                //reinitialize variable
        }
}

而在你的活动,为此,

And in your Activity, do this,

(HelloApplication)getApplication()).setGlobalVariable(10);
int valiable=((HelloApplication)getApplication()).getGlobalVariable();

从这里拍摄..

和谈论的共享preference,你应该考虑使用它们,只有当值必须保存很长一段时间。如果没有,你应该使用的应用程序类,并使用getter和setter方法​​是合法的方式来做到这一点。

And speak about SharedPreference, you should consider using them only when the value has to be stored for a long time. if not, you should make use of the Application class and use setters and getters which is the legitimate way to do this.