Cannot access the property delegate

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 =-))

1 Like

Try ::str.apply { isAccessible = true }.getDelegate().
It sets isAccessible on that particular instance of property reference only.

1 Like

It worked, thanks! Could you explain, please, why I need to set the flag only on one instance of reference?

That’s because every callable reference instance has its own “isAccessible” status in order to avoid long-range effects of changing accessibility throughout the program.

2 Likes