在Java中(安卓)静态类 - 使用或不使用静态、或不、Java

2023-09-12 22:18:59 作者:可不可以不勇敢

最近我已经开始开发的Java为Android。

Recently I have started development in Java for Android.

我的想法是创建一个静态类将加载吨的东西就开始和存储结果应用的一生。

My idea is to create one static class which will load ton of stuff on the beginning and store results for a lifetime of application.

我一直在阅读大量的如何共享活动的对象,我认为最好的将是创建一个静态类。你怎么看?我应该用另一种方法?我问,因为我看了很多反意见在互联网上。

I have been reading lot of how to share object between activities and I think the best will be to create one static class. What do you think? Should I use another approach? I am asking because I have read lot of counter opinions over the internet.

感谢你。

推荐答案

我假设你是一个类的引用的的静态字段的,而不是的静态类其中,因为Wyzard指出的那样,是完全不同的东西。根据经验,一般情况下,保持信息的静态字段不是Java的一个好主意。这样做的原因是,它prevents实例的不管它是你在类存储多个实例的能力。

I'm assuming that you were referring to static fields of a class, as opposed to static class which, as Wyzard pointed out, is something completely different. As a general rule of thumb, holding information in static fields is not a good idea in Java. The reason for this is that it prevents the ability to instantiate multiple instances of whatever it is you store in the class.

在一个Android应用程序,来处理已经存储的数据与应用程序本身是继承 android.app.Application 类,并用它来处理应用程序的全局数据:

In the specific case of an Android application, the best way to deal with the issue of having data stored associated with the application itself is to subclass the android.app.Application class and use it to handle application-global data:

class FooApplication extends Application
{
    private String privData;

    public String getPrivData() {
        return privData;
    }
}

然后需要声明的是这个类是你的主应用程序类(而不是默认的应用程序)。在应用程序的Andr​​oidManifest.xml 条目添加以下内容:

You then need to declare that this class is your main application class (instead of the default Application). In the application entry in AndroidManifest.xml add the following:

<application android:name="com.example.application.FooApplication"
             ...>
    ...
</application>

您可以再看看应用程序实例从任何地方你的应用程序中使用的方法 Context.getApplicationContext()这将是一个实例你的内应用子类:

You can then look up the application instance from anywhere inside your application using the method Context.getApplicationContext() which will be an instance of your Application subclass:

FooApplication app = (FooApplication)Context.getApplicationContext();
String privData = app.getPrivData();

根据从正在试图寻找应用程序的子类,您可能需要调用getApplicationContext()如果没有背景:

Depending on from where you are trying to look for subclass of "Application", you may have to invoke the "getApplicationContext()" without "Context":

FooApplication app = (FooApplication)getApplicationContext();
String privData = app.getPrivData();
 
精彩推荐
图片推荐