使用类存储在Java中的静态数据? [英] Using a class to store static data in Java?

查看:460
本文介绍了使用类存储在Java中的静态数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于使用类存储在Java中的静态数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆