0

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

2 Answers2

2

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
}
Andrei Tanana
  • 7,932
  • 1
  • 27
  • 36
  • The idea is perfect, but the code is not working as my expectation. The provided code will check only one property. I edited it like this. ` fun Any.isAnyEntityInitialized(): Boolean { this::class.declaredMemberProperties.forEach { property -> if(property.isLateinit && property.javaField?.get(this) == null) return false } return true } ` – Pemassi Jan 27 '21 at 06:08
1

Since Kotlin 1.2, there is already a function for that.

You can use the function: isInitialized docs

Code example:

lateinit var key: String

fun useKey() {
    check(::key.isInitialized) { "The field 'key' must be initialized" }
    // use key safely
}

Note: check will throw an IllegalStateException if the variable is not initialized.

Diego Magdaleno
  • 831
  • 8
  • 20