Search code examples
kotlinreflectionkotlin-reflectkotlin-lateinit

How to find is a lateinit var has been initialized via Reflection?


I want to find out via reflection if lateinit property of an object has been initialized. How do I got about doing that?

Getting the property and checking non-null results in UninitializedPropertyAccessException

fun Any.isAnyEntityInitialized () {
    val clazz = this.javaClass.kotlin
    val filteredEntities = clazz.declaredMemberProperties.filter {
        it.isLateinit && getDelegate(this) != null
    }
}

Solution

  • This works for me:

    import kotlin.reflect.full.declaredMemberProperties
    import kotlin.reflect.jvm.javaField
    
    class Test {
        lateinit var s: String
    }
    
    fun Any.isAnyEntityInitialized(): Boolean =
        this::class.declaredMemberProperties.any { property ->
            property.isLateinit && property.javaField?.get(this) != null
        }
    
    fun main() {
        val test = Test()
        println(test.isAnyEntityInitialized()) // prints false
        test.s = "test"
        println(test.isAnyEntityInitialized()) // prints true
    }