确实“反对"在科特林得到垃圾收集 [英] does "object" in kotlin get garbage collected

查看:58
本文介绍了确实“反对"在科特林得到垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个像这样的 Object

If we have an Object like this

object Repo { var activeMovies: ArrayList<Movie>? = null }

然后我们这样称呼它来分配值

and then we call it like this to assign a value

Repo.activeMovies = movieList

实例化它的活动完成后,它会收集垃圾吗?

after the Activity that instantiated it is finish, does it get Garbage Collected?

我知道这可能是一个非常基本的问题,但是如果object键入科特林,我将无法理解生命周期.

I know this may be very basic question but I cannot understand the lifecycle if the object type in Kotlin.

推荐答案

如果我们创建这样的对象:

If we create an object like this:

object Test {
    // some functions and properties
}

并将其反编译为 Java ,我们将看到下一个代码:

and decompile it to Java, we will see next code:

public final class Test {
    public static final Test INSTANCE;

   static {
      Test var0 = new Test();
      INSTANCE = var0;
   }
}

从反编译的代码中,我们可以看到object创建了一个 Singleton .初始化发生在静态块上.在 Java 中,静态块在类加载时执行. Test类的实例是在类加载器加载该类时创建的.这种方法可以保证延迟加载线程安全.单例对象的实例保存在该对象类内的静态字段中.因此,它不符合垃圾收集的条件. Test Singleton ,其寿命与应用程序的寿命一样长.

From the decompiled code, we can see that object creates a Singleton. The initialization happens on a static block. In Java, static blocks are executed on class loading time. The instance of Test class is created at the moment when the classloader loads the class. This approach guarantees lazy-loading and thread-safety. An instance of a singleton object is kept in a static field inside the class of that object. Therefore it isn’t eligible to the garbage collection. The Test is a Singleton, whose lifespan is as long as the lifespan of an app.

以下是一些有关静态变量的有用信息: Android静态对象生命周期返回到应用程序时的静态变量为空.

Here are some useful information about static variables Android static object lifecycle and static variable null when returning to the app.

这篇关于确实“反对"在科特林得到垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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