java 静态(类)变量的生命周期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6163828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:36:54  来源:igfitidea点击:

Lifetime of static (class) variables

javaandroidstatic

提问by anirvan

for quite some time i was blissfully of the opinion that static [instance] variables exist as long as the app runs. however, to my dismay, and much alarm, i feel that it's not true.

很长一段时间以来,我很高兴地认为只要应用程序运行,静态 [实例] 变量就存在。然而,令我沮丧和震惊的是,我觉得这不是真的。

for mere testing, i created a static list of strings, and in my main activityclass overrode the onDestroymethod to print a message to verify that the app exited. in the onCreatemethod i simply added a new string, and printed the contents of the list. what i've found is that the size of the list keeps on increasing, and all the string values added previously are still present.

仅仅为了测试,我创建了一个静态字符串列表,并在我的主activity类中覆盖了onDestroy打印消息以验证应用程序退出的方法。在onCreate方法中,我只是添加了一个新的string,并打印了列表的内容。我发现列表的大小不断增加,并且之前添加的所有字符串值仍然存在。

i've read in places [even here on SO] that the instance variables exist as long as the app does, but i fear it's not really so.

我读过一些地方[甚至在这里],只要应用程序存在,实例变量就存在,但我担心事实并非如此。

to be more precise, i came to be aware of this problem while using the Facebook SDK for Android. i've seen that the AuthListenerinstances within the list of listeners in the SessionEventsclass just keeps on increasing over time. Hence, whenever the app is launched and the user logs in using FB, the listener methods get triggered as many times as there are instances present in the SessionEventsclass.

更准确地说,我是在使用 Facebook SDK for Android 时意识到这个问题的。我已经看到类AuthListener中侦听器列表中的实例SessionEvents随着时间的推移不断增加。因此,每当应用程序启动并且用户使用 FB 登录时,侦听器方法都会触发与SessionEvents类中存在的实例一样多的次数。

Has someone observed this before, and is there some cardinal mistake i'm committing in understanding how android works?

之前是否有人观察过这一点,我是否在理解 android 的工作原理时犯了一些重大错误?

what gives?

是什么赋予了?

thanks for reading!

谢谢阅读!

[UPDATE]
I stand corrected by BalusCand rdineiu. I really didn't mean to create a confusion here about instance and class variables. Alas, in my haste to post my question i've committed a mistake i didn't wish to. I am very well aware of the difference between staticand instancevariables. I just intended to write classvariables, and can't quite figure out what came over to refer to static variables as instancevariables.

[更新]
我支持BalusCrdineiu。我真的不想在这里对实例和类变量造成混淆。唉,在我匆忙发布我的问题时,我犯了一个我不想犯的错误。我非常清楚staticinstance变量之间的区别。我只是想写class变量,并不能完全弄清楚是什么来将静态变量称为instance变量。

However, my question still stands. @MisterSquonk- no, i'm not confusing here about when my Activityends and when the app gets destroyed. Here's what I tried on a sample - I've got only ONE Activitywhich serves as the Main. When I press the back button from this Activity, I'm assuming the Activitygets removed from the stack andthe app also gets destroyed. I've launched the Task Manager to verify that my app is no longer running.

但是,我的问题仍然存在。 @MisterSquonk- 不,我不会在这里混淆我何时Activity结束以及应用程序何时被销毁。这是我在样本上的尝试 - 我只有一个Activity用作Main. 当我从 this 按下后退按钮时Activity,我假设Activity从堆栈中删除并且应用程序也被销毁。我启动了任务管理器来验证我的应用程序不再运行。

回答by rid

You seem to not make the distinction between static and instance variables. Static variables are defined on the class itself. Instance variables are present only in class instances.

您似乎没有区分静态变量和实例变量。静态变量是在类本身上定义的。实例变量只存在于类实例中。

Example:

例子:

class Test {
    public static int a;
}

The variable ais defined on the class itself, not on instances of the class. Each instance will access the samevariable. If one instance sets the value of ato 5, every other instance will see the value as 5. The variable will not vanish once the instance vanishes, because it is in no way tied to any instance (it's a class variable). It will continue to be there until the end of time (or until the application exits, whichever comes first).

变量a是在类本身上定义的,而不是在类的实例上。每个实例将访问相同的变量。如果一个实例将 的值设置a5,则其他所有实例都会将该值视为5。一旦实例消失,变量就不会消失,因为它与任何实例都没有任何联系(它是一个类变量)。它将继续存在直到时间结束(或直到应用程序退出,以先到者为准)。

On the other hand, the following example uses an instance variable:

另一方面,以下示例使用实例变量:

class Test {
    public int a;
}

This variable will be accessible only from instancesof the class. Each instance will have a different copy of the variable. Once the instance gets destroyed, the variable goes with it.

该变量只能从类的实例中访问。每个实例都有一个不同的变量副本。一旦实例被销毁,变量就会随之而来。



To illustrate:

为了显示:

import java.util.List;
import java.util.ArrayList;

class Test {
  // instanceVar will be initialized whenever a new Test object is created
  private List<Integer> instanceVar = new ArrayList<Integer>();

  // staticVar will be initialized right now
  private static List<Integer> staticVar = new ArrayList<Integer>();

  public void updateInstanceVar() {
    instanceVar.add(1);
    instanceVar.add(2);
  }

  public void updateStaticVar() {
    staticVar.add(1);
    staticVar.add(2);
  }

  public static void main(String[] args) {
    Test test1 = new Test();
    test1.updateInstanceVar(); // test1.instanceVar = [1, 2]
    test1.updateStaticVar();   // Test.staticVar    = [1, 2]

    Test test2 = new Test();
    test2.updateInstanceVar(); // test2.instanceVar = [1, 2]
    test2.updateStaticVar();   // Test.staticVar    = [1, 2, 1, 2]
  }
}

回答by anirvan

so - i had posted the same question [unfortunately making the same mistake of terming staticvariables as instancevariables] on the Android Developer Google group.

所以 - 我在 Android Developer Google group 上发布了同样的问题 [不幸的是,我犯了同样的错误,将static变量称为instance变量]。

I received some really good responses, especially from Kostya. My interactions on that group helped me to grasp the underlying "rules" of the Android platform.

我收到了一些非常好的回复,尤其是来自Kostya 的回复。我在那个小组的互动帮助我掌握了 Android 平台的基本“规则”。

Hope the message threadhelps you as well.

希望留言帖也能帮到你。

回答by Ha.

The instance variables are destroyed when app does but some gui widgets by default save their state and then restore it in onCreate method.

实例变量在 app 执行时被销毁,但一些 gui 小部件默认保存它们的状态,然后在 onCreate 方法中恢复它。