Java / Android静态私有变量的垃圾回收

3
假设我有一个以下定义的Fragment:
public class MyFragment extends Fragment {
   private static String sample = "";

   public static void setSample(String s) {
      sample = s;
   }
}

在应用程序的生命周期内,Sample 会被垃圾回收吗(无论是否存在对MyFragment的任何引用 - 我想这并不重要)?

3个回答

4

你说得没错,MyFragment 的实例数量并不重要。

sample 变量将在加载 MyFragment 的类加载器存在期间有效地成为垃圾收集根对象。

需要注意的是,变量永远不会被垃圾回收 - 对象会被回收。


3
只要类没有被卸载,示例变量就不会被垃圾回收。

只有在其定义类加载器可能被垃圾回收时,类或接口才能被卸载,如§12.6所述。由引导程序加载器加载的类和接口不能被卸载。


2

private static String sample

当代码中第一次引用它时(类加载器加载它),它将开始存在,并且将独立于现有对象引用而存在。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接