kotlinreflectionprivate-memberskotlin-reflect

How to access a Kotlin private top-level property in the unnamed (main) file?


How to use Java or Kotlin reflection to access the value of a private variable in the Main.kt file?

package com.example

private val myName = "abc"

fun main() {
    println(myName)    
}

Solution

  • val myName = Class
        .forName("com.example.MainKt") // Make sure to use the complete class name
        .getDeclaredField("myName")
        .apply { isAccessible = true }
        .get(null /* because a top-level property is static */) as String
    println(myName) // abc