静态类变量的生存期 [英] Lifetime of static class variables

查看:297
本文介绍了静态类变量的生存期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Checker {
    static private int value1 = 0, value2 = 1;

    static private Activity activity;

    public static void init(Activity activity) {
        Checker.activity = activity;

        value1 = // calculate value

        value2 = // calculate value, normally the same as value1
    }

    public static void check() {
        if (value1 != value2)
            activity.finish();
    }
}

我得到了上面的类,并放置调用Checker.init()的主要活动的onCreate,并在我的code的不同点调用Checker.check()。问题是,我在Checker.check()为activity.finish()时,重新打开该应用程序已被后台运行了一段时间后得到一个NullPointerException异常。

I got the above class and placed a call to Checker.init() in onCreate of the main activity and calls to Checker.check() at various points of my code. Problem is that I get a NullPointerException in Checker.check() for activity.finish() when re-opening the app after it has been backgrounded for some time.

通常值1 ==值2,所以这个例外似乎表明,所有静态变量是重置为默认值。我是一个Java / Android的新手,但我认为只要活动是在内存中的情况下,该活动被杀害的onCreate等Checker.init()再次调用这些变量都将保留。那么,为什么会出现这种情况?

Normally value1 == value2, so this exception seems to indicate that all the static variables were reset to default. I am a Java/Android newbie, but I thought these variables are retained as long as the activity is in memory and in case the activity is killed onCreate and so Checker.init() called again. So why does this happen?

推荐答案

根据您所描述的症状,什么是最有可能发生的是,检查的类加载器越来越垃圾收集,但你的活动不被垃圾收集。因此,当从背景应用程序返回时,活动进行到 onResume 。当调用 Checker.check()制成,在检查类重新装入<$的默认值C $ C>值1 和值2

Based on the symptoms you are describing, what's most likely happening is that the ClassLoader for Checker is getting garbage collected but your Activity is not being garbage collected. So when the app returns from the background, Activity goes to onResume. When the call to Checker.check() is made, the Checker class is reloaded with the default values of value1 and value2.

一个办法,以确保检查类,只要是活动保持活动类将检查实例的引用保持周围。当然,您也可以考虑重新设计检查功能,因此,它不依赖于静态成员的行为。

One way to make sure that the Checker class stays around as long as the Activity is to keep a reference to a Checker instance in the Activity class. Of course, you might also consider redesigning the Checker functionality so that it doesn't depend on static member behavior.

这篇关于静态类变量的生存期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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