Skip to content

Instantly share code, notes, and snippets.

@mehdiyari
Created March 1, 2022 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdiyari/b512fc8ff64dd8c05e20fa05af4b5890 to your computer and use it in GitHub Desktop.
Save mehdiyari/b512fc8ff64dd8c05e20fa05af4b5890 to your computer and use it in GitHub Desktop.
This gist is part of meta-programming with kotlin articles
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