Created
March 1, 2022 08:17
-
-
Save mehdiyari/b512fc8ff64dd8c05e20fa05af4b5890 to your computer and use it in GitHub Desktop.
This gist is part of meta-programming with kotlin articles
This file contains 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
fun main() { | |
val singletonKClass = Singleton::class | |
singletonKClass.constructors.firstOrNull { it.visibility == KVisibility.PRIVATE }?.also { privateConstructor -> | |
/** | |
* We give access to private constructor and we can create instance | |
* from [Singleton] class [privateConstructor.call] method | |
*/ | |
privateConstructor.isAccessible = true | |
val singletonNewObject = privateConstructor.call() | |
singletonKClass.declaredMemberProperties.firstOrNull { it.visibility == KVisibility.PRIVATE }?.also { dataProperty -> | |
/** | |
* We give access to private property and we can get value with [dataProperty.get] method. | |
*/ | |
dataProperty.isAccessible = true | |
dataProperty.get(singletonNewObject).toString().also(::println) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment