Last active
July 26, 2024 15:32
-
-
Save brozikcz/546d68a3cfc535b13c2106230458aedf to your computer and use it in GitHub Desktop.
How to keep lazy delegate in uninitialized state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #_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