I’m trying to get the delegate of a property, but JVM throws an error to me: Exception in thread "main" kotlin.reflect.full.IllegalPropertyDelegateAccessException: Cannot obtain the delegate of a non-accessible property. Use "isAccessible = true" to make the property accessible
My code is:
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaField
import kotlin.reflect.jvm.javaGetter
import kotlin.reflect.jvm.javaSetter
class MyDelegatedProperty {
var innerStr: String = ""
operator fun getValue(thisRef: Any, property: KProperty<*>): String {
return innerStr
}
operator fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
innerStr = value
}
fun doSomething() {
println(innerStr)
}
}
class Example {
var str: String by MyDelegatedProperty()
fun doSomething() {
Example::str.javaField!!.isAccessible = true
Example::str.javaGetter!!.isAccessible = true
Example::str.javaSetter!!.isAccessible = true
::str.isAccessible = true
val delegate = ::str.getDelegate() as MyDelegatedProperty
delegate.doSomething()
}
}
fun main() {
val example = Example()
example.str = "test"
example.doSomething()
}
Please, help me to explain the JVM that my delegate IS accessible =-))