I noticed an inconsistent behavior in reflection methods when trying to access some static properties of types in java.lang
via reflection.
I’ll provide further details below.
The main question here is: am I missing something or is there some bug in the reflection library?
Details
On Kotlin JVM Kotlin, some basic types (e.g. Long
, Int
, etc) come with a companion object letting developers access static properties and methods of the corresponding JVM types.
Accordingly, Kotlin reflection lets developers access such a companion object, as it would for any Kotlin class exposing a companion object.
However, when accessing some properties, exceptions are thrown unexpectedly.
Consider for instance the case of Int.MAX_VALUE
:
val member = Int::class.companionObject?.members?.firstOrNull { it.name == "MAX_VALUE" }
assertEquals(Int.MAX_VALUE, member?.call()) // throws kotlin.reflect.jvm.internal.KotlinReflectionInternalError:
// No accessor found for property val kotlin.Int.Companion.MAX_VALUE: kotlin.Int
A similar issue occurs when accessing Int.MIN_VALUE
as a property:
val property = Int::class.companionObject?.memberProperties?.firstOrNull { it.name == "MIN_VALUE" }
assertEquals(Int.MIN_VALUE, property?.call()) // throws kotlin.reflect.jvm.internal.KotlinReflectionInternalError:
// No accessor found for property val kotlin.Int.Companion.MIN_VALUE: kotlin.Int
Notably, a similar issue occurs when accessing Array.size
, even if it does not corresponds to a static method:
val member = Array::class.members.firstOrNull { it.name == "size" }
val instance = arrayOf("A")
assertEquals(instance.size, member?.call(instance)) // kotlin.reflect.jvm.internal.KotlinReflectionInternalError:
// No accessor found for property val kotlin.Array<T>.size: kotlin.Int