0

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)    
}
1

1 Answer 1

0
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.