Skip to content

Instantly share code, notes, and snippets.

@brozikcz
Last active July 26, 2024 15:32
Show Gist options
  • Save brozikcz/546d68a3cfc535b13c2106230458aedf to your computer and use it in GitHub Desktop.
Save brozikcz/546d68a3cfc535b13c2106230458aedf to your computer and use it in GitHub Desktop.
How to keep lazy delegate in uninitialized state
#_deviceId is lazy variable in the AnalyticsUtils class
private fun restoreLazy(execute: () -> Unit) {
AnalyticsUtils::class.java.declaredFields
.first { it.name.contains("_deviceId") }!!
.let { field ->
field.isAccessible = true
val lazy = field.get(field)
val initializer = lazy::class.java.getDeclaredField("initializer").apply {
isAccessible = true
}
val initializerValue = initializer.get(lazy)
execute.invoke()
val uninitializedValue = Class.forName("kotlin.UNINITIALIZED_VALUE").getDeclaredField("INSTANCE").run {
isAccessible = true
get(this)
}
lazy::class.java.getDeclaredField("_value").run {
isAccessible = true
set(lazy, uninitializedValue)
}
initializer.set(lazy, initializerValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment