【发布时间】:2018-07-06 11:56:10
【问题描述】:
我为Any 类型编写了一个扩展函数,它将通过名称检索对象属性值。我希望能够在我的项目中的任何地方使用它。这是我的扩展功能:
package com.example.core.utils.validation
import java.util.NoSuchElementException
import kotlin.reflect.full.memberProperties
fun Any.getFieldValue(fieldName: String): Any? {
try {
return this.javaClass.kotlin.memberProperties.first { it.name == fieldName }.get(this)
} catch (e: NoSuchElementException) {
throw NoSuchFieldException(fieldName)
}
}
现在我想这样使用它
package com.example.core
import com.example.core.utils.validation.*
class App {
val obj = object {
val field = "value"
}
val fieldValue = obj.getFieldValue("field")
}
但是有未解决的参考错误
我应该如何使我的扩展函数全局化并将其导入到任何地方?
【问题讨论】:
-
看起来它应该对我有用...两者都在一个项目中吗?