在 Kotlin 中,您可以使用伴随对象创建单例:
class MyClass {
companion object {
fun doSomething() {
}
}
}
根据 Kotlin 文档,它指出:
Note that, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects...
https://kotlinlang.org/docs/reference/object-declarations.html
这是否意味着在伴生对象中使用函数后,类 (MyClass) 的实例在应用程序的整个生命周期中都保留在内存中? Android Studio 有没有办法检查是否是这种情况?
最佳答案
instance of the class (MyClass) remains in memory for the entire lifecycle of the app?
JVM 中的伴生对象
在 Kotlin 中
class MyClass {
companion object {
fun doSomething() {
}
}
}
JVM 中转换的 MyClass(Kotlin)
public final class MyClass {
public static final MyClass.Companion Companion = new MyClass.Companion(null);
public static final class Companion {
public final void doSomething() {
}
private Companion() {
}
public Companion() {
this();
}
}
}
如上面的代码,companion object
在 JVM 中被声明为 Companion
类,并在 MyClass< 中创建为
类。因此,不被 gc 收集。因此,对象(Companion)的内存在static
字段ProcessLifecycle
期间保留。 静态最终对象
在正常情况下不会被释放。
总之,如果在应用程序中引用 MyClass.Companion
实例,该实例将不会被垃圾回收。 (在一般类加载器上)。
*如果应用程序中没有引用MyClass.Companion
实例,它可能会被代码收缩功能删除。
Is there a way in Android Studio to check to see if this is the case?
可以通过android studio > profiler > Heap dump查看。
引用
关于android - 在应用程序的生命周期中,伴随对象是否保留在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59679479/