检查 class 的所有 lateinit 成员是否已经初始化
check whether all lateinit members of a class have been initialized
我想创建一个扩展方法来帮助我验证 class 的所有 lateinit
属性是否已在给定时间点初始化。
到目前为止,我已经想出了以下内容:
fun Any.assertLateInitPropertiesAreInitialized() {
for (member in this::class.memberProperties) {
if (member.isLateinit) {
try {
member.call(this)
}
catch (e: Throwable) {
if (e.cause is UninitializedPropertyAccessException) {
throw e
}
}
}
}
}
但它很难看,因为我必须显式调用 属性,这可能非常昂贵。
有没有办法改用 isInitialized
?我不知道如何 bind 我的 KProperty1
到 this
以获得 KProperty0
所以我访问它(如果它在一切皆有可能)。
由于 lateinit
属性不能为空,检查 Java 字段是否为 null
应该就足够了。类似于:
member.javaField!!.get(this) != null
我想创建一个扩展方法来帮助我验证 class 的所有 lateinit
属性是否已在给定时间点初始化。
到目前为止,我已经想出了以下内容:
fun Any.assertLateInitPropertiesAreInitialized() {
for (member in this::class.memberProperties) {
if (member.isLateinit) {
try {
member.call(this)
}
catch (e: Throwable) {
if (e.cause is UninitializedPropertyAccessException) {
throw e
}
}
}
}
}
但它很难看,因为我必须显式调用 属性,这可能非常昂贵。
有没有办法改用 isInitialized
?我不知道如何 bind 我的 KProperty1
到 this
以获得 KProperty0
所以我访问它(如果它在一切皆有可能)。
由于 lateinit
属性不能为空,检查 Java 字段是否为 null
应该就足够了。类似于:
member.javaField!!.get(this) != null