Reflection in programming is a program's ability to introspect its own source code symbols at runtime. For example, it might be used to display all of a class’s properties, like in the displayPropertiesAsList function below.
//sampleStart
// import kotlin.reflect.full.memberProperties // replaced by reflect-lite
fun displayPropertiesAsList(value: Any) {
value::class.memberProperties
.sortedBy { it.name }
.map { p -> " * ${p.name}: ${p.call(value)}" }
.forEach(::println)
}
class Person(
val name: String,
val surname: String,
val children: Int,
val female: Boolean,
)
class Dog(
val name: String,
val age: Int,
)
enum class DogBreed {
HUSKY, LABRADOR, PUG, BORDER_COLLIE
}
fun main() {
val granny = Person("Esmeralda", "Weatherwax", 0, true)
displayPropertiesAsList(granny)
// * children: 0
// * female: true
// * name: Esmeralda
// * surname: Weatherwax
val cookie = Dog("Cookie", 1)
displayPropertiesAsList(cookie)
// * age: 1
// * name: Cookie
displayPropertiesAsList(DogBreed.BORDER_COLLIE)
// * name: BORDER_COLLIE
// * ordinal: 3
}
//sampleEnd
// ===== reflect-lite =====
// A small stand-in for the part of kotlin-reflect that is declared as extensions
// (kotlin.reflect.full, kotlin.reflect.jvm), for environments where kotlin-reflect.jar
// is not on the classpath. It reads the kotlin.Metadata annotation and uses Java reflection.
// Members of KClass and of callable references (members, constructors, parameters, call...)
// belong to the standard library and cannot be replaced.
private val rlPredefined = listOf(
"kotlin/Any", "kotlin/Nothing", "kotlin/Unit", "kotlin/Throwable", "kotlin/Number",
"kotlin/Byte", "kotlin/Double", "kotlin/Float", "kotlin/Int", "kotlin/Long", "kotlin/Short",
"kotlin/Boolean", "kotlin/Char", "kotlin/CharSequence", "kotlin/String", "kotlin/Comparable",
"kotlin/Enum", "kotlin/Array", "kotlin/ByteArray", "kotlin/DoubleArray", "kotlin/FloatArray",
"kotlin/IntArray", "kotlin/LongArray", "kotlin/ShortArray", "kotlin/BooleanArray",
"kotlin/CharArray", "kotlin/Cloneable", "kotlin/Annotation", "kotlin/collections/Iterable",
"kotlin/collections/MutableIterable", "kotlin/collections/Collection",
"kotlin/collections/MutableCollection", "kotlin/collections/List",
"kotlin/collections/MutableList", "kotlin/collections/Set", "kotlin/collections/MutableSet",
"kotlin/collections/Map", "kotlin/collections/MutableMap", "kotlin/collections/Map.Entry",
"kotlin/collections/MutableMap.MutableEntry", "kotlin/collections/Iterator",
"kotlin/collections/MutableIterator", "kotlin/collections/ListIterator",
"kotlin/collections/MutableListIterator",
)
private class RlPb(val b: ByteArray, var p: Int, val end: Int) {
fun varint(): Long {
var r = 0L
var s = 0
while (true) {
val x = b[p++].toInt()
r = r or ((x and 0x7F).toLong() shl s)
if (x and 0x80 == 0) return r
s += 7
}
}
/** Calls [f] with (field number, varint value, nested message or null). */
inline fun each(f: (Int, Long, RlPb?) -> Unit) {
while (p < end) {
val tag = varint().toInt()
when (tag and 7) {
0 -> f(tag ushr 3, varint(), null)
2 -> { val len = varint().toInt(); val sub = RlPb(b, p, p + len); p += len; f(tag ushr 3, 0, sub) }
1 -> p += 8
5 -> p += 4
else -> return
}
}
}
fun packed(): List<Int> = buildList { while (p < end) add(varint().toInt()) }
}
class RlMType(val nullable: Boolean, val className: String?, val args: List<RlMArg>)
class RlMArg(val projection: Int, val type: RlMType?) // 0 in, 1 out, 2 invariant, 3 star
class RlMParam(val name: String, val optional: Boolean, val type: RlMType?, val isVararg: Boolean)
class RlMCtor(val secondary: Boolean, val params: List<RlMParam>)
class RlMProp(val name: String, val type: RlMType?, val flags: Int, val isExtension: Boolean = false)
class RlMFun(val name: String, val params: List<RlMParam>, val ret: RlMType?, val flags: Int, val isExtension: Boolean = false)
class RlMClass(val flags: Int, val ctors: List<RlMCtor>, val props: List<RlMProp>, val funs: List<RlMFun>)
private fun rlDecode(d1: Array<String>): ByteArray {
if (d1.isEmpty()) return ByteArray(0)
val all = d1.joinToString("")
if (all.isEmpty()) return ByteArray(0)
if (all[0] == '\u0000') return ByteArray(all.length - 1) { all[it + 1].code.toByte() }
val s = if (all[0] == '') all.substring(1) else all
val bytes = ByteArray(s.length) { ((s[it].code + 0x7f) and 0x7f).toByte() }
val out = ByteArray(7 * bytes.size / 8)
var bi = 0
var bit = 0
for (i in out.indices) {
val first = (bytes[bi].toInt() and 0xff) ushr bit
bi++
val second = (bytes[bi].toInt() and ((1 shl (bit + 1)) - 1)) shl (7 - bit)
out[i] = (first + second).toByte()
if (bit == 6) { bi++; bit = 0 } else bit++
}
return out
}
private val rlMetaCache = java.util.concurrent.ConcurrentHashMap<Class<*>, java.util.Optional<RlMClass>>()
fun rlMeta(c: Class<*>): RlMClass? = rlMetaCache.getOrPut(c) {
java.util.Optional.ofNullable(runCatching { rlParse(c) }.getOrNull())
}.orElse(null)
private fun rlParse(c: Class<*>): RlMClass? {
val m = c.getAnnotation(Metadata::class.java) ?: return null
if (m.kind != 1) return null
val bytes = rlDecode(m.data1)
val d2 = m.data2
val top = RlPb(bytes, 0, bytes.size)
val tableLen = top.varint().toInt()
val table = RlPb(bytes, top.p, top.p + tableLen)
top.p += tableLen
class Rec(val predefined: Int?, val string: String?, val op: Int, val sub: List<Int>, val rep: List<Int>)
val records = ArrayList<Rec>()
table.each { n, _, sub ->
if (n == 1 && sub != null) {
var range = 1; var pre: Int? = null; var str: String? = null; var op = 0
var subs = emptyList<Int>(); var reps = emptyList<Int>()
sub.each { f, v, s ->
when (f) {
1 -> range = v.toInt()
2 -> pre = v.toInt()
3 -> op = v.toInt()
4 -> subs = s?.packed() ?: subs + v.toInt()
5 -> reps = s?.packed() ?: reps + v.toInt()
6 -> if (s != null) str = String(bytes, s.p, s.end - s.p, Charsets.UTF_8)
}
}
repeat(range) { records.add(Rec(pre, str, op, subs, reps)) }
}
}
fun str(i: Int): String {
val r = records.getOrNull(i)
var s = r?.string ?: r?.predefined?.let { rlPredefined.getOrNull(it) } ?: d2.getOrNull(i) ?: "?"
if (r != null) {
if (r.sub.size >= 2 && r.sub[0] in 0..r.sub[1] && r.sub[1] <= s.length) s = s.substring(r.sub[0], r.sub[1])
if (r.rep.size >= 2) s = s.replace(r.rep[0].toChar(), r.rep[1].toChar())
when (r.op) {
1 -> s = s.replace('$', '.')
2 -> { if (s.length >= 2) s = s.substring(1, s.length - 1); s = s.replace('$', '.') }
}
}
return s
}
val typeTable = ArrayList<RlMType>()
var firstNullable = -1
fun type(pb: RlPb): RlMType {
var nullable = false; var cls: String? = null
val args = ArrayList<RlMArg>()
pb.each { f, v, s ->
when (f) {
2 -> if (s != null) {
var proj = 2; var t: RlMType? = null
s.each { af, av, asub ->
when (af) {
1 -> proj = av.toInt()
2 -> if (asub != null) t = type(asub)
3 -> t = typeTable.getOrNull(av.toInt())
}
}
args.add(RlMArg(proj, t))
}
3 -> nullable = v != 0L
6 -> cls = str(v.toInt())
}
}
return RlMType(nullable, cls, args)
}
fun tableType(id: Int): RlMType? = typeTable.getOrNull(id)?.let {
if (firstNullable in 0..id && !it.nullable) RlMType(true, it.className, it.args) else it
}
fun param(pb: RlPb): RlMParam {
var flags = 0; var name = "?"; var t: RlMType? = null; var vararg = false
pb.each { f, v, s ->
when (f) {
1 -> flags = v.toInt()
2 -> name = str(v.toInt())
3 -> if (s != null) t = type(s)
5 -> t = tableType(v.toInt())
4, 6 -> vararg = true
}
}
return RlMParam(name, flags and 2 != 0, t, vararg)
}
// Two passes: the type table (field 30) may come after the declarations that use it.
RlPb(bytes, top.p, bytes.size).each { n, _, sub ->
if (n == 30 && sub != null) sub.each { f, v, s ->
if (f == 1 && s != null) typeTable.add(type(s))
if (f == 2) firstNullable = v.toInt()
}
}
var classFlags = 6
val ctors = ArrayList<RlMCtor>(); val props = ArrayList<RlMProp>(); val funs = ArrayList<RlMFun>()
RlPb(bytes, top.p, bytes.size).each { n, v, sub ->
when {
n == 1 -> classFlags = v.toInt()
n == 8 && sub != null -> {
var flags = 6; val ps = ArrayList<RlMParam>()
sub.each { f, fv, s -> if (f == 1) flags = fv.toInt(); if (f == 2 && s != null) ps.add(param(s)) }
ctors.add(RlMCtor(flags and 16 != 0, ps))
}
n == 10 && sub != null -> {
var flags = 518; var name = "?"; var t: RlMType? = null; var ext = false
sub.each { f, fv, s ->
when (f) {
11 -> flags = fv.toInt()
2 -> name = str(fv.toInt())
3 -> if (s != null) t = type(s)
9 -> t = tableType(fv.toInt())
5, 10 -> ext = true
}
}
props.add(RlMProp(name, t, flags, ext))
}
n == 9 && sub != null -> {
var flags = 6; var name = "?"; var t: RlMType? = null; val ps = ArrayList<RlMParam>(); var ext = false
sub.each { f, fv, s ->
when (f) {
9 -> flags = fv.toInt()
2 -> name = str(fv.toInt())
3 -> if (s != null) t = type(s)
7 -> t = tableType(fv.toInt())
6 -> if (s != null) ps.add(param(s))
5, 8 -> ext = true
}
}
funs.add(RlMFun(name, ps, t, flags, ext))
}
}
}
return RlMClass(classFlags, ctors, props, funs)
}
private fun rlErasure(t: java.lang.reflect.Type): Class<*> = when (t) {
is Class<*> -> t
is java.lang.reflect.ParameterizedType -> t.rawType as Class<*>
is java.lang.reflect.WildcardType -> rlErasure(t.upperBounds.firstOrNull() ?: Any::class.java)
is java.lang.reflect.GenericArrayType -> java.lang.reflect.Array.newInstance(rlErasure(t.genericComponentType), 0).javaClass
is java.lang.reflect.TypeVariable<*> -> rlErasure(t.bounds.firstOrNull() ?: Any::class.java)
else -> Any::class.java
}
class RlType(val javaType: java.lang.reflect.Type, val meta: RlMType?, private val forceNullable: Boolean? = null, private val givenArguments: List<kotlin.reflect.KTypeProjection>? = null) : kotlin.reflect.KType {
override val classifier: kotlin.reflect.KClassifier get() = rlErasure(javaType).kotlin
override val isMarkedNullable: Boolean get() = forceNullable ?: meta?.nullable ?: false
override val annotations: List<Annotation> get() = emptyList()
override val arguments: List<kotlin.reflect.KTypeProjection>
get() {
if (givenArguments != null) return givenArguments
val jArgs = (javaType as? java.lang.reflect.ParameterizedType)?.actualTypeArguments
val n = jArgs?.size ?: meta?.args?.size ?: 0
return List(n) { i ->
val ma = meta?.args?.getOrNull(i)
val ja = jArgs?.getOrNull(i)
if (ma?.projection == 3 || (ma == null && ja is java.lang.reflect.WildcardType && ja.lowerBounds.isEmpty() && ja.upperBounds.singleOrNull() == Any::class.java)) {
kotlin.reflect.KTypeProjection.STAR
} else {
val bound = when (ja) {
is java.lang.reflect.WildcardType -> ja.lowerBounds.firstOrNull() ?: ja.upperBounds.firstOrNull() ?: Any::class.java
null -> Any::class.java
else -> ja
}
val t = RlType(bound, ma?.type)
when (ma?.projection) {
0 -> kotlin.reflect.KTypeProjection.contravariant(t)
1 -> kotlin.reflect.KTypeProjection.covariant(t)
else -> kotlin.reflect.KTypeProjection.invariant(t)
}
}
}
}
override fun equals(other: Any?): Boolean = other is kotlin.reflect.KType && classifier == other.classifier &&
arguments == other.arguments && isMarkedNullable == other.isMarkedNullable
override fun hashCode(): Int = (classifier.hashCode() * 31 + arguments.hashCode()) * 31 + (if (isMarkedNullable) 1 else 0)
override fun toString(): String {
val name = meta?.className?.replace('/', '.') ?: (classifier as kotlin.reflect.KClass<*>).qualifiedName ?: rlErasure(javaType).name
val args = arguments.takeIf { it.isNotEmpty() }?.joinToString(", ", "<", ">") ?: ""
return name + args + if (isMarkedNullable) "?" else ""
}
}
class RlParameter(
override val index: Int,
override val name: String?,
override val type: kotlin.reflect.KType,
override val kind: kotlin.reflect.KParameter.Kind,
override val isOptional: Boolean,
override val isVararg: Boolean,
override val annotations: List<Annotation>,
private val callable: Any? = null,
) : kotlin.reflect.KParameter {
override fun equals(other: Any?): Boolean = other is RlParameter && index == other.index && callable == other.callable
override fun hashCode(): Int = index * 31 + callable.hashCode()
override fun toString(): String = when (kind) {
kotlin.reflect.KParameter.Kind.INSTANCE -> "instance parameter"
else -> "parameter #$index $name"
} + " of ..."
}
private fun rlVisibility(mod: Int): kotlin.reflect.KVisibility = when {
java.lang.reflect.Modifier.isPublic(mod) -> kotlin.reflect.KVisibility.PUBLIC
java.lang.reflect.Modifier.isProtected(mod) -> kotlin.reflect.KVisibility.PROTECTED
java.lang.reflect.Modifier.isPrivate(mod) -> kotlin.reflect.KVisibility.PRIVATE
else -> kotlin.reflect.KVisibility.INTERNAL
}
// Like kotlin-reflect, exceptions thrown by the called code arrive wrapped in InvocationTargetException.
private inline fun <R> rlInvoke(block: () -> R): R = block()
private fun rlDefault(c: Class<*>): Any? = when (c) {
java.lang.Boolean.TYPE -> false
java.lang.Character.TYPE -> 0.toChar()
java.lang.Byte.TYPE -> 0.toByte()
java.lang.Short.TYPE -> 0.toShort()
java.lang.Integer.TYPE -> 0
java.lang.Float.TYPE -> 0f
java.lang.Long.TYPE -> 0L
java.lang.Double.TYPE -> 0.0
else -> null
}
abstract class RlCallable<R> : kotlin.reflect.KCallable<R> {
var accessible: Boolean = false
override val typeParameters: List<kotlin.reflect.KTypeParameter> get() = emptyList()
override val isSuspend: Boolean get() = false
override val isFinal: Boolean get() = true
override val isOpen: Boolean get() = false
override val isAbstract: Boolean get() = false
protected fun checkAccess(member: java.lang.reflect.AccessibleObject, mod: Int) {
if (!java.lang.reflect.Modifier.isPublic(mod)) {
if (!accessible) throw IllegalStateException("Class can not access a member with modifiers \"${java.lang.reflect.Modifier.toString(mod)}\". Set isAccessible = true first.")
member.isAccessible = true
} else {
runCatching { member.isAccessible = true }
}
}
}
/** A constructor or a member function. */
class RlFunction<R>(
private val owner: Class<*>,
val javaConstructor: java.lang.reflect.Constructor<*>?,
val javaMethod: java.lang.reflect.Method?,
private val metaParams: List<RlMParam>?,
private val metaReturn: RlMType?,
private val suspendFlag: Boolean = false,
) : RlCallable<R>(), kotlin.reflect.KFunction<R> {
private val exec: java.lang.reflect.Executable get() = javaConstructor ?: javaMethod!!
override val name: String get() = javaMethod?.name ?: "<init>"
override val isInline: Boolean get() = false
override val isExternal: Boolean get() = false
override val isOperator: Boolean get() = false
override val isInfix: Boolean get() = false
override val isSuspend: Boolean get() = suspendFlag
override val isFinal: Boolean get() = java.lang.reflect.Modifier.isFinal(exec.modifiers) || javaConstructor != null
override val isOpen: Boolean get() = !isFinal && !isAbstract
override val isAbstract: Boolean get() = java.lang.reflect.Modifier.isAbstract(exec.modifiers)
override val visibility: kotlin.reflect.KVisibility get() = rlVisibility(exec.modifiers)
override val annotations: List<Annotation> get() = exec.annotations.toList()
override val returnType: kotlin.reflect.KType
get() = if (javaConstructor != null) RlType(owner, null) else RlType(javaMethod!!.genericReturnType, metaReturn)
private val hasInstance: Boolean get() = javaMethod != null && !java.lang.reflect.Modifier.isStatic(javaMethod.modifiers)
override val parameters: List<kotlin.reflect.KParameter> by lazy {
val types = exec.genericParameterTypes
val annotations = exec.parameterAnnotations
val instance = if (hasInstance) listOf(RlParameter(0, null, RlType(owner, null), kotlin.reflect.KParameter.Kind.INSTANCE, false, false, emptyList(), exec)) else emptyList()
instance + List(metaParams?.size ?: types.size) { i ->
val mp = metaParams?.getOrNull(i)
RlParameter(i + instance.size, mp?.name ?: "arg$i", RlType(types[i], mp?.type), kotlin.reflect.KParameter.Kind.VALUE, mp?.optional ?: false, mp?.isVararg ?: false, annotations.getOrNull(i)?.toList() ?: emptyList(), exec)
}
}
@Suppress("UNCHECKED_CAST")
override fun call(vararg args: Any?): R = rlInvoke {
checkAccess(exec, exec.modifiers)
if (javaConstructor != null) javaConstructor.newInstance(*args) as R
else if (hasInstance) javaMethod!!.invoke(args[0], *args.drop(1).toTypedArray()) as R
else javaMethod!!.invoke(null, *args) as R
}
@Suppress("UNCHECKED_CAST")
override fun callBy(args: Map<kotlin.reflect.KParameter, Any?>): R {
val missing = parameters.filter { it !in args }
missing.firstOrNull { !it.isOptional }?.let { throw IllegalArgumentException("No argument provided for a required parameter: $it") }
if (missing.isEmpty()) return call(*parameters.map { args[it] }.toTypedArray())
val values = parameters.filter { it.kind == kotlin.reflect.KParameter.Kind.VALUE }
val types = exec.parameterTypes
val masks = IntArray((values.size + 31) / 32)
val actual = values.mapIndexed { i, p ->
if (p in args) args[p] else { masks[i / 32] = masks[i / 32] or (1 shl (i % 32)); rlDefault(types[i]) }
}
return rlInvoke {
if (javaConstructor != null) {
val synthetic = owner.declaredConstructors.firstOrNull {
it.parameterCount == types.size + masks.size + 1 && it.parameterTypes.take(types.size) == types.toList() &&
it.parameterTypes.last().name == "kotlin.jvm.internal.DefaultConstructorMarker"
} ?: throw UnsupportedOperationException("reflect-lite: no constructor with default arguments found in ${owner.name}")
synthetic.isAccessible = true
synthetic.newInstance(*(actual + masks.toList() + listOf(null)).toTypedArray()) as R
} else {
val instance = if (hasInstance) listOf(args[parameters[0]]) else emptyList()
val synthetic = owner.declaredMethods.firstOrNull {
it.name == javaMethod!!.name + "\$default" && it.parameterCount == instance.size + types.size + masks.size + 1
} ?: throw UnsupportedOperationException("reflect-lite: no function with default arguments found for ${javaMethod!!.name}")
synthetic.isAccessible = true
synthetic.invoke(null, *(instance + actual + masks.toList() + listOf(null)).toTypedArray()) as R
}
}
}
override fun equals(other: Any?): Boolean = other is RlFunction<*> && exec == other.exec
override fun hashCode(): Int = exec.hashCode()
override fun toString(): String {
val ps = parameters.filter { it.kind == kotlin.reflect.KParameter.Kind.VALUE }.joinToString(", ") { it.type.toString() }
val receiver = if (hasInstance) "${owner.kotlin.qualifiedName ?: owner.name}." else ""
return if (javaConstructor != null) "fun `<init>`($ps): $returnType" else "fun $receiver$name($ps): $returnType"
}
}
open class RlProperty<T, V>(
val owner: Class<*>,
val meta: RlMProp,
val javaGetter: java.lang.reflect.Method?,
val javaSetter: java.lang.reflect.Method?,
val javaField: java.lang.reflect.Field?,
) : RlCallable<V>(), kotlin.reflect.KProperty1<T, V> {
var displayOwner: Class<*> = owner
override val name: String get() = meta.name
override val isLateinit: Boolean get() = meta.flags and (1 shl 12) != 0
override val isConst: Boolean get() = meta.flags and (1 shl 11) != 0
override val isFinal: Boolean get() = javaGetter?.let { java.lang.reflect.Modifier.isFinal(it.modifiers) } ?: true
override val isOpen: Boolean get() = !isFinal && !isAbstract
override val isAbstract: Boolean get() = javaGetter?.let { java.lang.reflect.Modifier.isAbstract(it.modifiers) } ?: false
override val visibility: kotlin.reflect.KVisibility
get() = rlVisibility(javaGetter?.modifiers ?: javaField?.modifiers ?: java.lang.reflect.Modifier.PRIVATE)
override val returnType: kotlin.reflect.KType
get() = RlType(javaGetter?.genericReturnType ?: javaField?.genericType ?: Any::class.java, meta.type)
override val parameters: List<kotlin.reflect.KParameter>
get() = listOf(RlParameter(0, null, RlType(owner, null), kotlin.reflect.KParameter.Kind.INSTANCE, false, false, emptyList(), this))
override val annotations: List<Annotation>
get() {
val getterName = if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) name else "get" + name.replaceFirstChar { it.uppercaseChar() }
val holder = owner.declaredMethods.firstOrNull { it.name == "$getterName\$annotations" }
return holder?.annotations?.filter { it.annotationClass != Deprecated::class && it.annotationClass.java != java.lang.Deprecated::class.java } ?: emptyList()
}
@Suppress("UNCHECKED_CAST")
override fun get(receiver: T): V = rlInvoke {
if (javaGetter != null) { checkAccess(javaGetter, javaGetter.modifiers); javaGetter.invoke(receiver) as V }
else { val f = javaField ?: throw UnsupportedOperationException("reflect-lite: property $name has no getter and no field"); checkAccess(f, f.modifiers); f.get(receiver) as V }
}
override fun invoke(p1: T): V = get(p1)
@Suppress("UNCHECKED_CAST")
override fun call(vararg args: Any?): V = get(args[0] as T)
@Suppress("UNCHECKED_CAST")
override fun callBy(args: Map<kotlin.reflect.KParameter, Any?>): V = get(args.values.single() as T)
override fun getDelegate(receiver: T): Any? = throw UnsupportedOperationException("reflect-lite: getDelegate is not supported")
override val getter: kotlin.reflect.KProperty1.Getter<T, V>
get() = throw UnsupportedOperationException("reflect-lite: property accessors are not supported, use get/set")
override fun equals(other: Any?): Boolean = other is RlProperty<*, *> && owner == other.owner && name == other.name
override fun hashCode(): Int = owner.hashCode() * 31 + name.hashCode()
override fun toString(): String = "${if (this is kotlin.reflect.KMutableProperty<*>) "var" else "val"} ${displayOwner.kotlin.qualifiedName ?: displayOwner.name}.$name: $returnType"
}
class RlMutableProperty<T, V>(owner: Class<*>, meta: RlMProp, g: java.lang.reflect.Method?, s: java.lang.reflect.Method?, f: java.lang.reflect.Field?) :
RlProperty<T, V>(owner, meta, g, s, f), kotlin.reflect.KMutableProperty1<T, V> {
override fun set(receiver: T, value: V) {
rlInvoke {
if (javaSetter != null) { checkAccess(javaSetter, javaSetter.modifiers); javaSetter.invoke(receiver, value) }
else { val f = javaField ?: throw UnsupportedOperationException("reflect-lite: property $name has no setter and no field"); checkAccess(f, f.modifiers); f.set(receiver, value) }
}
}
override val setter: kotlin.reflect.KMutableProperty1.Setter<T, V>
get() = throw UnsupportedOperationException("reflect-lite: property accessors are not supported, use get/set")
}
private fun rlGetterName(name: String): String =
if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) name else "get" + name.replaceFirstChar { it.uppercaseChar() }
private fun rlSetterName(name: String): String =
"set" + (if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) name.substring(2) else name.replaceFirstChar { it.uppercaseChar() })
private val rlPropertyCache = java.util.concurrent.ConcurrentHashMap<Class<*>, List<kotlin.reflect.KProperty1<*, *>>>()
// Cached, so that isAccessible set on a property is remembered, as in kotlin-reflect.
@Suppress("UNCHECKED_CAST")
private fun <T : Any> rlDeclaredProperties(c: Class<*>): List<kotlin.reflect.KProperty1<T, *>> =
rlPropertyCache.getOrPut(c) { rlReadProperties<Any>(c) } as List<kotlin.reflect.KProperty1<T, *>>
private fun <T : Any> rlReadProperties(c: Class<*>): List<kotlin.reflect.KProperty1<T, *>> {
val meta = rlMeta(c) ?: return emptyList()
return meta.props.filter { !it.isExtension }.sortedBy { it.name }.map { p ->
val getter = c.declaredMethods.firstOrNull { it.name.substringBefore('-') == rlGetterName(p.name) && it.parameterCount == 0 && !it.isSynthetic }
val setter = c.declaredMethods.firstOrNull { it.name.substringBefore('-') == rlSetterName(p.name) && it.parameterCount == 1 && !it.isSynthetic }
val field = runCatching { c.getDeclaredField(p.name) }.getOrNull() ?: runCatching { c.getDeclaredField(p.name + "\$delegate") }.getOrNull()
if (p.flags and (1 shl 8) != 0) RlMutableProperty<T, Any?>(c, p, getter, setter, field) else RlProperty<T, Any?>(c, p, getter, setter, field)
}
}
private fun rlSupers(c: Class<*>): List<Class<*>> = buildList {
fun visit(x: Class<*>) { if (x !in this) { add(x); x.superclass?.let(::visit); x.interfaces.forEach(::visit) } }
visit(c)
}
val <T : Any> kotlin.reflect.KClass<T>.declaredMemberProperties: Collection<kotlin.reflect.KProperty1<T, *>>
get() = rlDeclaredProperties(java)
val <T : Any> kotlin.reflect.KClass<T>.memberProperties: Collection<kotlin.reflect.KProperty1<T, *>>
get() {
val seen = HashSet<String>()
return rlSupers(java).flatMap { rlDeclaredProperties<T>(it) }
.filter { it.visibility != kotlin.reflect.KVisibility.PRIVATE || (it as RlProperty<*, *>).owner == java }
.filter { seen.add(it.name) }
}
private fun rlDeclaredFunctions(c: Class<*>): List<kotlin.reflect.KFunction<*>> {
val meta = rlMeta(c) ?: return emptyList()
return meta.funs.filter { !it.isExtension }.sortedBy { it.name }.mapNotNull { f ->
val suspend = f.flags and (1 shl 14) != 0
val count = f.params.size + if (suspend) 1 else 0
val m = c.declaredMethods.firstOrNull { it.name.substringBefore('-') == f.name && it.parameterCount == count && !it.isSynthetic && !java.lang.reflect.Modifier.isStatic(it.modifiers) }
m?.let { RlFunction<Any?>(c, null, it, f.params, f.ret, suspend) }
}
}
val kotlin.reflect.KClass<*>.declaredMemberFunctions: Collection<kotlin.reflect.KFunction<*>> get() = rlDeclaredFunctions(java)
val kotlin.reflect.KClass<*>.memberFunctions: Collection<kotlin.reflect.KFunction<*>>
get() {
val seen = HashSet<String>()
val own = rlSupers(java).filter { it != Any::class.java }.flatMap { rlDeclaredFunctions(it) }
.filter { seen.add(it.name + (it as RlFunction<*>).javaMethod!!.parameterTypes.joinToString { p -> p.name }) }
val any = listOf("equals", "hashCode", "toString").filter { n -> own.none { it.name == n } }.map { n ->
val m = Any::class.java.declaredMethods.first { it.name == n }
val ps = if (n == "equals") listOf(RlMParam("other", false, RlMType(true, "kotlin/Any", emptyList()), false)) else emptyList()
RlFunction<Any?>(Any::class.java, null, m, ps, null)
}
return own + any
}
val <T : Any> kotlin.reflect.KClass<T>.primaryConstructor: kotlin.reflect.KFunction<T>?
get() {
val meta = rlMeta(java) ?: return null
val primary = meta.ctors.firstOrNull { !it.secondary } ?: return null
val candidates = java.declaredConstructors.filter { !it.isSynthetic && it.parameterCount == primary.params.size }
val ctor = candidates.singleOrNull() ?: candidates.firstOrNull() ?: return null
return RlFunction(java, ctor, null, primary.params, null)
}
@Suppress("UNCHECKED_CAST")
fun <T : Any> kotlin.reflect.KClass<T>.createInstance(): T {
val noArg = java.declaredConstructors.firstOrNull { it.parameterCount == 0 }
if (noArg != null) return rlInvoke { noArg.isAccessible = true; noArg.newInstance() as T }
val primary = primaryConstructor?.takeIf { c -> c.parameters.all { it.isOptional } }
?: throw IllegalArgumentException("Class should have a single no-arg constructor: $this")
return primary.callBy(emptyMap())
}
fun rlAnnotations(e: kotlin.reflect.KAnnotatedElement): List<Annotation> = when (e) {
is kotlin.reflect.KClass<*> -> e.java.annotations.filter { it !is Metadata }
is RlCallable<*>, is RlParameter, is RlType -> e.annotations
is kotlin.jvm.internal.CallableReference -> rlLite(e)?.annotations ?: emptyList()
else -> e.annotations
}
inline fun <reified A : Annotation> kotlin.reflect.KAnnotatedElement.findAnnotation(): A? =
rlAnnotations(this).filterIsInstance<A>().firstOrNull()
inline fun <reified A : Annotation> kotlin.reflect.KAnnotatedElement.findAnnotations(): List<A> =
rlAnnotations(this).filterIsInstance<A>()
inline fun <reified A : Annotation> kotlin.reflect.KAnnotatedElement.hasAnnotation(): Boolean = findAnnotation<A>() != null
/** The reflect-lite counterpart of a callable reference such as `User::name`, or null. */
fun rlLite(ref: kotlin.jvm.internal.CallableReference): RlCallable<*>? {
val ownerClass = (ref.owner as? kotlin.reflect.KClass<*>)?.java ?: return null
return when (ref) {
is kotlin.reflect.KProperty<*> -> rlSupers(ownerClass).flatMap { rlDeclaredProperties<Any>(it) }.firstOrNull { it.name == ref.name } as RlCallable<*>?
is kotlin.reflect.KFunction<*> ->
if (ref.name == "<init>") ownerClass.kotlin.primaryConstructor as RlCallable<*>?
else ownerClass.kotlin.memberFunctions.firstOrNull { it.name == ref.name } as RlCallable<*>?
else -> null
}
}
var <T> kotlin.reflect.KCallable<T>.isAccessible: Boolean
get() = (this as? RlCallable<*>)?.accessible ?: true
set(value) {
(this as? RlCallable<*> ?: throw UnsupportedOperationException("reflect-lite: isAccessible works only on members obtained from memberProperties, memberFunctions or primaryConstructor")).accessible = value
}
val kotlin.reflect.KType.jvmErasure: kotlin.reflect.KClass<*>
get() = classifier as? kotlin.reflect.KClass<*> ?: Any::class
fun kotlin.reflect.KType.withNullability(nullable: Boolean): kotlin.reflect.KType = when (this) {
is RlType -> RlType(javaType, meta, nullable, arguments)
else -> if (isMarkedNullable == nullable) this else RlType((classifier as kotlin.reflect.KClass<*>).javaObjectType, null, nullable, arguments)
}
val kotlin.reflect.KClass<*>.superclasses: List<kotlin.reflect.KClass<*>>
get() = (listOfNotNull(java.superclass) + java.interfaces).map { it.kotlin }.ifEmpty { if (java == Any::class.java) emptyList() else listOf(Any::class) }
val kotlin.reflect.KClass<*>.allSuperclasses: Collection<kotlin.reflect.KClass<*>>
get() = rlSupers(java).drop(1).map { it.kotlin }
fun kotlin.reflect.KClass<*>.isSubclassOf(base: kotlin.reflect.KClass<*>): Boolean = base.javaObjectType.isAssignableFrom(javaObjectType)
fun kotlin.reflect.KClass<*>.isSuperclassOf(derived: kotlin.reflect.KClass<*>): Boolean = derived.isSubclassOf(this)
private fun rlCompanion(c: Class<*>): Any? =
c.declaredFields.firstOrNull { java.lang.reflect.Modifier.isStatic(it.modifiers) && it.type.enclosingClass == c && it.type.simpleName == it.name }
?.let { it.isAccessible = true; it.get(null) }
val kotlin.reflect.KClass<*>.companionObjectInstance: Any? get() = rlCompanion(java)
val kotlin.reflect.KClass<*>.companionObject: kotlin.reflect.KClass<*>? get() = companionObjectInstance?.let { it::class }
val kotlin.reflect.KProperty<*>.javaField: java.lang.reflect.Field?
get() = ((this as? RlProperty<*, *>) ?: (this as? kotlin.jvm.internal.CallableReference)?.let { rlLite(it) } as? RlProperty<*, *>)?.javaField
val kotlin.reflect.KProperty<*>.javaGetter: java.lang.reflect.Method?
get() = ((this as? RlProperty<*, *>) ?: (this as? kotlin.jvm.internal.CallableReference)?.let { rlLite(it) } as? RlProperty<*, *>)?.javaGetter
val kotlin.reflect.KFunction<*>.javaMethod: java.lang.reflect.Method? get() = (this as? RlFunction<*>)?.javaMethod
val <T> kotlin.reflect.KFunction<T>.javaConstructor: java.lang.reflect.Constructor<*>? get() = (this as? RlFunction<*>)?.javaConstructor
val kotlin.reflect.KClass<*>.functions: Collection<kotlin.reflect.KFunction<*>> get() = memberFunctions
val kotlin.reflect.KClass<*>.declaredFunctions: Collection<kotlin.reflect.KFunction<*>> get() = declaredMemberFunctions
val kotlin.reflect.KClass<*>.declaredMembers: Collection<kotlin.reflect.KCallable<*>> get() = declaredMemberFunctions + declaredMemberProperties
/** A member extension property: only its name, type and value are supported. */
class RlProperty2<D, E, V>(private val owner: Class<*>, private val meta: RlMProp, private val javaGetter: java.lang.reflect.Method?) :
RlCallable<V>(), kotlin.reflect.KProperty2<D, E, V> {
override val name: String get() = meta.name
override val isLateinit: Boolean get() = false
override val isConst: Boolean get() = false
override val visibility: kotlin.reflect.KVisibility get() = rlVisibility(javaGetter?.modifiers ?: java.lang.reflect.Modifier.PRIVATE)
override val returnType: kotlin.reflect.KType get() = RlType(javaGetter?.genericReturnType ?: Any::class.java, meta.type)
override val annotations: List<Annotation> get() = emptyList()
override val parameters: List<kotlin.reflect.KParameter>
get() = listOf(
RlParameter(0, null, RlType(owner, null), kotlin.reflect.KParameter.Kind.INSTANCE, false, false, emptyList(), this),
RlParameter(1, null, RlType(javaGetter?.genericParameterTypes?.firstOrNull() ?: Any::class.java, null), kotlin.reflect.KParameter.Kind.EXTENSION_RECEIVER, false, false, emptyList(), this),
)
@Suppress("UNCHECKED_CAST")
override fun get(receiver1: D, receiver2: E): V {
val g = javaGetter ?: throw UnsupportedOperationException("reflect-lite: property $name has no getter")
checkAccess(g, g.modifiers)
return g.invoke(receiver1, receiver2) as V
}
override fun invoke(p1: D, p2: E): V = get(p1, p2)
@Suppress("UNCHECKED_CAST")
override fun call(vararg args: Any?): V = get(args[0] as D, args[1] as E)
@Suppress("UNCHECKED_CAST")
override fun callBy(args: Map<kotlin.reflect.KParameter, Any?>): V = get(args[parameters[0]] as D, args[parameters[1]] as E)
override fun getDelegate(receiver1: D, receiver2: E): Any? = throw UnsupportedOperationException("reflect-lite: getDelegate is not supported")
override val getter: kotlin.reflect.KProperty2.Getter<D, E, V>
get() = throw UnsupportedOperationException("reflect-lite: property accessors are not supported, use get")
override fun toString(): String = "val ${owner.kotlin.qualifiedName ?: owner.name}.(${parameters[1].type}.)$name: $returnType"
}
private fun <T : Any> rlExtensionProperties(c: Class<*>): List<kotlin.reflect.KProperty2<T, *, *>> {
val meta = rlMeta(c) ?: return emptyList()
return meta.props.filter { it.isExtension }.sortedBy { it.name }.map { p ->
RlProperty2<T, Any?, Any?>(c, p, c.declaredMethods.firstOrNull { it.name == rlGetterName(p.name) && it.parameterCount == 1 && !it.isSynthetic })
}
}
val <T : Any> kotlin.reflect.KClass<T>.declaredMemberExtensionProperties: Collection<kotlin.reflect.KProperty2<T, *, *>>
get() = rlExtensionProperties(java)
val <T : Any> kotlin.reflect.KClass<T>.memberExtensionProperties: Collection<kotlin.reflect.KProperty2<T, *, *>>
get() = rlSupers(java).flatMap { rlExtensionProperties<T>(it) }.distinctBy { it.name }
/** An approximation: compares classes and nullability; type arguments must be equal or star-projected. */
fun kotlin.reflect.KType.isSubtypeOf(other: kotlin.reflect.KType): Boolean {
if (isMarkedNullable && !other.isMarkedNullable) return false
val mine = classifier as? kotlin.reflect.KClass<*> ?: return false
val theirs = other.classifier as? kotlin.reflect.KClass<*> ?: return false
if (!theirs.javaObjectType.isAssignableFrom(mine.javaObjectType)) return false
if (mine != theirs || other.arguments.isEmpty()) return true
return arguments.size == other.arguments.size && arguments.zip(other.arguments).all { (a, b) ->
val at = a.type
val bt = b.type
bt == null || (at != null && when (b.variance) {
kotlin.reflect.KVariance.OUT -> at.isSubtypeOf(bt)
kotlin.reflect.KVariance.IN -> bt.isSubtypeOf(at)
else -> at == bt || bt == at
})
}
}
fun kotlin.reflect.KType.isSupertypeOf(other: kotlin.reflect.KType): Boolean = other.isSubtypeOf(this)
val java.lang.reflect.Field.kotlinProperty: kotlin.reflect.KProperty<*>?
get() = declaringClass.kotlin.declaredMemberProperties.firstOrNull { (it as RlProperty<*, *>).javaField == this }
val java.lang.reflect.Method.kotlinFunction: kotlin.reflect.KFunction<*>?
get() = declaringClass.kotlin.declaredMemberFunctions.firstOrNull { (it as RlFunction<*>).javaMethod == this }
val <T : Any> java.lang.reflect.Constructor<T>.kotlinFunction: kotlin.reflect.KFunction<T>?
get() = declaringClass.kotlin.primaryConstructor?.takeIf { (it as RlFunction<*>).javaConstructor == this }
val kotlin.reflect.KProperty<*>.javaSetter: java.lang.reflect.Method?
get() = ((this as? RlProperty<*, *>) ?: (this as? kotlin.jvm.internal.CallableReference)?.let { rlLite(it) } as? RlProperty<*, *>)?.javaSetter
// ===== end of reflect-lite =====
Reflection is often used by libraries that analyze our code and behave according to how it is constructed. Let's see a few examples.
Libraries like Gson use reflection to serialize and deserialize objects. These libraries often reference classes to check which properties they require and which constructors they offer in order to then use these constructors. Later in this chapter, we will implement our own serializer.
data class Car(val brand: String, val doors: Int)
fun main() {
val json = "{\"brand\":\"Jeep\", \"doors\": 3}"
val gson = Gson()
val car: Car = gson.fromJson(json, Car::class.java)
println(car) // Car(brand=Jeep, doors=3)
val newJson = gson.toJson(car)
println(newJson) // {"brand":"Jeep", "doors": 3}
}
As another example, we can see the Koin dependency injection framework, which uses reflection to identify the type that should be injected and to create and inject an instance appropriately.
class MyActivity : Application() {
val myPresenter: MyPresenter by inject()
}
Reflection is extremely useful, so let's start learning how we can use it ourselves.
To use Kotlin reflection, we need to add the kotlin-reflect dependency to our project. It is not needed to reference an element, but we need it for the majority of operations on element references. If you see KotlinReflectionNotSupportedError, it means the kotlin-reflect dependency is required. In the code examples in this chapter, I assume this dependency is included.
Hierarchy of classes
Before we get into the details, let's first review the general type hierarchy of element references.
Notice that all the types in this hierarchy start with the K prefix. This indicates that this type is part of Kotlin Reflection and differentiates these classes from Java Reflection. The type Class is part of Java Reflection, so Kotlin called its equivalent KClass.
At the top of this hierarchy, you can find KAnnotatedElement. Element is a term that includes classes, functions, and properties, so it includes everything we can reference. All elements can be annotated, which is why this interface includes the annotations property, which we can use to get element annotations.
interface KAnnotatedElement {
val annotations: List<Annotation>
}
The next confusing thing you might have noticed is that there is no type to represent interfaces. This is because interfaces in reflection API nomenclature are also considered classes, so their references are of type KClass. This might be confusing, but it is really convenient.
Now we can get into the details, which is not easy because everything is connected to nearly everything else. At the same time, using the reflection API is really intuitive and easy to learn. Nevertheless, I decided that to help you understand this API better I’ll do something I generally avoid doing: we will go through the essential classes and discuss their methods and properties. In between, I will show you some practical examples and explain some essential reflection concepts.
Function references
We reference functions using a double colon and a function name. Member references start with the type specified before colons.
import kotlin.reflect.*
fun printABC() {
println("ABC")
}
fun double(i: Int): Int = i * 2
class Complex(val real: Double, val imaginary: Double) {
fun plus(number: Number): Complex = Complex(
real = real + number.toDouble(),
imaginary = imaginary
)
}
fun Complex.double(): Complex =
Complex(real * 2, imaginary * 2)
fun Complex?.isNullOrZero(): Boolean =
this == null || (this.real == 0.0 && this.imaginary == 0.0)
class Box<T>(var value: T) {
fun get(): T = value
}
fun <T> Box<T>.set(value: T) {
this.value = value
}
fun main() {
val f1 = ::printABC
val f2 = ::double
val f3 = Complex::plus
val f4 = Complex::double
val f5 = Complex?::isNullOrZero
val f6 = Box<Int>::get
val f7 = Box<String>::set
}
The result type from the function reference is an appropriate KFunctionX, where X indicates the number of parameters. This type also includes type parameters for each function parameter and the result. For instance, the printABC reference type is KFunction0<Unit>. For method references, a receiver is considered another parameter, so the Complex::double type is KFunction1<Complex, Complex>.
// ...
fun main() {
val f1: KFunction0<Unit> = ::printABC
val f2: KFunction1<Int, Int> = ::double
val f3: KFunction2<Complex, Number, Complex> = Complex::plus
val f4: KFunction1<Complex, Complex> = Complex::double
val f5: KFunction1<Complex?, Boolean> = Complex?::isNullOrZero
val f6: KFunction1<Box<Int>, Int> = Box<Int>::get
val f7: KFunction2<Box<String>, String, Unit>=Box<String>::set
}
Alternatively, you can reference methods on concrete instances. These are so-called bounded function references, and they are represented with the same type but without additional parameters for the receiver.
// ...
fun main() {
val c = Complex(1.0, 2.0)
val f3: KFunction1<Number, Complex> = c::plus
val f4: KFunction0<Complex> = c::double
val f5: KFunction0<Boolean> = c::isNullOrZero
val b = Box(123)
val f6: KFunction0<Int> = b::get
val f7: KFunction1<Int, Unit> = b::set
}
All the specific types representing function references implement the KFunction type, with only one type parameter representing the function result type (because every function must have a result type in Kotlin).
// ...
fun main() {
val f1: KFunction<Unit> = ::printABC
val f2: KFunction<Int> = ::double
val f3: KFunction<Complex> = Complex::plus
val f4: KFunction<Complex> = Complex::double
val f5: KFunction<Boolean> = Complex?::isNullOrZero
val f6: KFunction<Int> = Box<Int>::get
val f7: KFunction<Unit> = Box<String>::set
val c = Complex(1.0, 2.0)
val f8: KFunction<Complex> = c::plus
val f9: KFunction<Complex> = c::double
val f10: KFunction<Boolean> = c::isNullOrZero
val b = Box(123)
val f11: KFunction<Int> = b::get
val f12: KFunction<Unit> = b::set
}
Now, what can we do with function references? In a previous book from this series, Functional Kotlin, I showed that they can be used instead of lambda expressions where a function type is expected, like in the example below, where function references are used as arguments to filterNot, map, and reduce.
Using function references where a function type is expected is not "real" reflection because, under the hood, Kotlin transforms these references to lambda expressions. We use function references like this only for our own convenience.
Formally, this is possible because types that represent function references, like KFunction2<Int, Int, Int>, implement function types; in this example, the implemented type is (Int, Int) -> Int. So, these types also include the invoke operator function, which lets the reference be called like a function.
fun add(i: Int, j: Int) = i + j
fun main() {
val f: KFunction2<Int, Int, Int> = ::add
println(f(1, 2)) // 3
println(f.invoke(1, 2)) // 3
}
The KFunction by itself includes only a few properties that let us check some function-specific characteristics:
isInline: Boolean - true if this function is inline.
isExternal: Boolean - true if this function is external.
isOperator: Boolean - true if this function is operator.
isInfix: Boolean - true if this function is infix.
isSuspend: Boolean - true if this is a suspending function.
KCallable has many more properties and a few functions. Let's start with the properties:
name: String - The name of this callable as declared in the source code. If the callable has no name, a special invented name is created. Here are some atypical cases:
constructors have the name "<init>",
property accessors: the getter for a property named "foo" will have the name "<get-foo>"; similarly the setter will have the name "<set-foo>".
parameters: List<KParameter> - a list of references to the parameters of this callable. We will discuss parameter references in a dedicated section.
returnType: KType - the type that is expected as a result of this callable call. We will discuss the KType type in a dedicated section.
typeParameters: List<KTypeParameter> - a list of generic type parameters of this callable. We will discuss the KTypeParameter type in the section dedicated to class references.
visibility: KVisibility? - visibility of this callable, or null if its visibility cannot be represented in Kotlin. KVisibility is an enum class with values PUBLIC, PROTECTED, INTERNAL, and PRIVATE.
isFinal: Boolean - true if this callable is final.
isOpen: Boolean - true if this function is open.
isAbstract: Boolean - true if this function is abstract.
isSuspend: Boolean - true if this is a suspending function (it is defined in both KFunction and KCallable).
import kotlin.reflect.KCallable
operator fun String.times(times: Int) = this.repeat(times)
fun main() {
val f: KCallable<String> = String::times
println(f.name) // times
println(f.parameters.map { it.name }) // [null, times]
println(f.returnType) // kotlin.String
println(f.typeParameters) // []
println(f.visibility) // PUBLIC
println(f.isFinal) // true
println(f.isOpen) // false
println(f.isAbstract) // false
println(f.isSuspend) // false
}
KCallable also has two methods that can be used to call it. The first one, call, accepts a vararg number of parameters of type Any? and the result type R, which is the only KCallable type parameter. When we call the call method, we need to provide a proper number of values with appropriate types, otherwise, it throws IllegalArgumentException. Optional arguments must also have a value specified when we use the call function.
import kotlin.reflect.KCallable
fun add(i: Int, j: Int) = i + j
fun main() {
val f: KCallable<Int> = ::add
println(f.call(1, 2)) // 3
println(f.call("A", "B")) // IllegalArgumentException
}
The second function, callBy, is used to call functions using named arguments. As an argument, it expects a map from KParameter to Any? that should include all non-optional arguments.
import kotlin.reflect.KCallable
fun sendEmail(
email: String,
title: String = "",
message: String = ""
) {
println(
"""
Sending to $email
Title: $title
Message: $message
""".trimIndent()
)
}
fun main() {
val f: KCallable<Unit> = ::sendEmail
f.callBy(mapOf(f.parameters[0] to "ABC"))
// Sending to ABC
// Title:
// Message:
val params = f.parameters.associateBy { it.name }
f.callBy(
mapOf(
params["title"]!! to "DEF",
params["message"]!! to "GFI",
params["email"]!! to "ABC",
)
)
// Sending to ABC
// Title: DEF
// Message: GFI
f.callBy(mapOf()) // throws IllegalArgumentException
}
Parameter references
The KCallable type has the parameters property, with a list of references of type KParameter. This type includes the following properties:
index: Int - the index of this parameter.
name: String? - a simple parameter name, or null if the parameter has no name or its name is not available at runtime. Examples of nameless parameters include a this instance for member functions, an extension receiver for extension functions or properties, and parameters of Java methods compiled without debug information.
type: KType - the type of this parameter.
kind: Kind - the kind of this parameter, which can be one of the following:
VALUE for regular parameters.
EXTENSION_RECEIVER for extension receivers.
INSTANCE for dispatch receivers, so instances needed to make member callable calls.
isOptional: Boolean - true if this parameter is optional, therefore it has a default argument specified.
isVararg: Boolean - true if this parameter is vararg.
As an example of how the parameters property can be used, I created the callWithFakeArgs function, which can be used to call a function reference with some constant values for the non-optional parameters of supported types. As you can see in the code below, this function takes parameters; it uses filterNot to keep only parameters that are not optional, and it then associates a value with each of them . A constant value is provided by the fakeValueFor function, which for Int always returns 123; for String, it constructs a fake value that includes a parameter name (the typeOf function will be described later in this chapter). The resulting map of parameters with associated values is used as an argument to callBy. You can see how this callWithFakeArgs can be used to execute different functions with the same arguments.
import kotlin.reflect.KCallable
import kotlin.reflect.KParameter
import kotlin.reflect.typeOf
fun callWithFakeArgs(callable: KCallable<*>) {
val arguments = callable.parameters
.filterNot { it.isOptional }
.associateWith { fakeValueFor(it) }
callable.callBy(arguments)
}
fun fakeValueFor(parameter: KParameter) =
when (parameter.type) {
typeOf<String>() -> "Fake ${parameter.name}"
typeOf<Int>() -> 123
else -> error("Unsupported type")
}
fun sendEmail(
email: String,
title: String,
message: String = ""
) {
println(
"""
Sending to $email
Title: $title
Message: $message
""".trimIndent()
)
}
fun printSum(a: Int, b: Int) {
println(a + b)
}
fun Int.printProduct(b: Int) {
println(this * b)
}
fun main() {
callWithFakeArgs(::sendEmail)
// Sending to Fake email
// Title: Fake title
// Message:
callWithFakeArgs(::printSum) // 246
callWithFakeArgs(Int::printProduct) // 15129
}
Property references
Property references are similar to function references, but they have a slightly more complicated type hierarchy.
All property references implement KProperty, which implements KCallable. Calling a property means calling its getter. Read-write property references implement KMutableProperty, which implements KProperty. There are also specific types like KProperty0 or KMutableProperty1, which specify how many receivers property calls require:
Read-only top-level properties implement KProperty0 because their getter can be called without any receiver.
Read-only member or extension properties implement KProperty1 because their getter needs a single receiver object.
Read-only member extension properties implement KProperty2 because their getter needs two receivers: a dispatch receiver and an extension receiver.
Read-write top-level properties implement KMutableProperty0 because their getter can be called without any receiver.
Read-write member or extension properties implement KMutableProperty1 because their getter and setter need a single receiver object.
Read-write member extension properties implement KMutableProperty2 because their getter and setter need two receivers: a dispatch receiver and an extension receiver.
Properties are referenced just like functions: use two colons before their name and an additional class name for member properties. There is no syntax to reference member extension functions or member extension properties; so, to show the KProperty2 example in the example below, I needed to find it in the class reference, which will be described in the next section.
//sampleStart
import kotlin.reflect.*
// import kotlin.reflect.full.memberExtensionProperties // replaced by reflect-lite
val lock: Any = Any()
var str: String = "ABC"
class Box(
var value: Int = 0
) {
val Int.addedToBox
get() = Box(value + this)
}
fun main() {
val p1: KProperty0<Any> = ::lock
println(p1) // val lock: kotlin.Any
val p2: KMutableProperty0<String> = ::str
println(p2) // var str: kotlin.String
val p3: KMutableProperty1<Box, Int> = Box::value
println(p3) // var Box.value: kotlin.Int
val p4: KProperty2<Box, *, *> = Box::class
.memberExtensionProperties
.first()
println(p4) // val Box.(kotlin.Int.)addedToBox: Box
}
//sampleEnd
// ===== reflect-lite =====
// A small stand-in for the part of kotlin-reflect that is declared as extensions
// (kotlin.reflect.full, kotlin.reflect.jvm), for environments where kotlin-reflect.jar
// is not on the classpath. It reads the kotlin.Metadata annotation and uses Java reflection.
// Members of KClass and of callable references (members, constructors, parameters, call...)
// belong to the standard library and cannot be replaced.
private val rlPredefined = listOf(
"kotlin/Any", "kotlin/Nothing", "kotlin/Unit", "kotlin/Throwable", "kotlin/Number",
"kotlin/Byte", "kotlin/Double", "kotlin/Float", "kotlin/Int", "kotlin/Long", "kotlin/Short",
"kotlin/Boolean", "kotlin/Char", "kotlin/CharSequence", "kotlin/String", "kotlin/Comparable",
"kotlin/Enum", "kotlin/Array", "kotlin/ByteArray", "kotlin/DoubleArray", "kotlin/FloatArray",
"kotlin/IntArray", "kotlin/LongArray", "kotlin/ShortArray", "kotlin/BooleanArray",
"kotlin/CharArray", "kotlin/Cloneable", "kotlin/Annotation", "kotlin/collections/Iterable",
"kotlin/collections/MutableIterable", "kotlin/collections/Collection",
"kotlin/collections/MutableCollection", "kotlin/collections/List",
"kotlin/collections/MutableList", "kotlin/collections/Set", "kotlin/collections/MutableSet",
"kotlin/collections/Map", "kotlin/collections/MutableMap", "kotlin/collections/Map.Entry",
"kotlin/collections/MutableMap.MutableEntry", "kotlin/collections/Iterator",
"kotlin/collections/MutableIterator", "kotlin/collections/ListIterator",
"kotlin/collections/MutableListIterator",
)
private class RlPb(val b: ByteArray, var p: Int, val end: Int) {
fun varint(): Long {
var r = 0L
var s = 0
while (true) {
val x = b[p++].toInt()
r = r or ((x and 0x7F).toLong() shl s)
if (x and 0x80 == 0) return r
s += 7
}
}
/** Calls [f] with (field number, varint value, nested message or null). */
inline fun each(f: (Int, Long, RlPb?) -> Unit) {
while (p < end) {
val tag = varint().toInt()
when (tag and 7) {
0 -> f(tag ushr 3, varint(), null)
2 -> { val len = varint().toInt(); val sub = RlPb(b, p, p + len); p += len; f(tag ushr 3, 0, sub) }
1 -> p += 8
5 -> p += 4
else -> return
}
}
}
fun packed(): List<Int> = buildList { while (p < end) add(varint().toInt()) }
}
class RlMType(val nullable: Boolean, val className: String?, val args: List<RlMArg>)
class RlMArg(val projection: Int, val type: RlMType?) // 0 in, 1 out, 2 invariant, 3 star
class RlMParam(val name: String, val optional: Boolean, val type: RlMType?, val isVararg: Boolean)
class RlMCtor(val secondary: Boolean, val params: List<RlMParam>)
class RlMProp(val name: String, val type: RlMType?, val flags: Int, val isExtension: Boolean = false)
class RlMFun(val name: String, val params: List<RlMParam>, val ret: RlMType?, val flags: Int, val isExtension: Boolean = false)
class RlMClass(val flags: Int, val ctors: List<RlMCtor>, val props: List<RlMProp>, val funs: List<RlMFun>)
private fun rlDecode(d1: Array<String>): ByteArray {
if (d1.isEmpty()) return ByteArray(0)
val all = d1.joinToString("")
if (all.isEmpty()) return ByteArray(0)
if (all[0] == '\u0000') return ByteArray(all.length - 1) { all[it + 1].code.toByte() }
val s = if (all[0] == '') all.substring(1) else all
val bytes = ByteArray(s.length) { ((s[it].code + 0x7f) and 0x7f).toByte() }
val out = ByteArray(7 * bytes.size / 8)
var bi = 0
var bit = 0
for (i in out.indices) {
val first = (bytes[bi].toInt() and 0xff) ushr bit
bi++
val second = (bytes[bi].toInt() and ((1 shl (bit + 1)) - 1)) shl (7 - bit)
out[i] = (first + second).toByte()
if (bit == 6) { bi++; bit = 0 } else bit++
}
return out
}
private val rlMetaCache = java.util.concurrent.ConcurrentHashMap<Class<*>, java.util.Optional<RlMClass>>()
fun rlMeta(c: Class<*>): RlMClass? = rlMetaCache.getOrPut(c) {
java.util.Optional.ofNullable(runCatching { rlParse(c) }.getOrNull())
}.orElse(null)
private fun rlParse(c: Class<*>): RlMClass? {
val m = c.getAnnotation(Metadata::class.java) ?: return null
if (m.kind != 1) return null
val bytes = rlDecode(m.data1)
val d2 = m.data2
val top = RlPb(bytes, 0, bytes.size)
val tableLen = top.varint().toInt()
val table = RlPb(bytes, top.p, top.p + tableLen)
top.p += tableLen
class Rec(val predefined: Int?, val string: String?, val op: Int, val sub: List<Int>, val rep: List<Int>)
val records = ArrayList<Rec>()
table.each { n, _, sub ->
if (n == 1 && sub != null) {
var range = 1; var pre: Int? = null; var str: String? = null; var op = 0
var subs = emptyList<Int>(); var reps = emptyList<Int>()
sub.each { f, v, s ->
when (f) {
1 -> range = v.toInt()
2 -> pre = v.toInt()
3 -> op = v.toInt()
4 -> subs = s?.packed() ?: subs + v.toInt()
5 -> reps = s?.packed() ?: reps + v.toInt()
6 -> if (s != null) str = String(bytes, s.p, s.end - s.p, Charsets.UTF_8)
}
}
repeat(range) { records.add(Rec(pre, str, op, subs, reps)) }
}
}
fun str(i: Int): String {
val r = records.getOrNull(i)
var s = r?.string ?: r?.predefined?.let { rlPredefined.getOrNull(it) } ?: d2.getOrNull(i) ?: "?"
if (r != null) {
if (r.sub.size >= 2 && r.sub[0] in 0..r.sub[1] && r.sub[1] <= s.length) s = s.substring(r.sub[0], r.sub[1])
if (r.rep.size >= 2) s = s.replace(r.rep[0].toChar(), r.rep[1].toChar())
when (r.op) {
1 -> s = s.replace('$', '.')
2 -> { if (s.length >= 2) s = s.substring(1, s.length - 1); s = s.replace('$', '.') }
}
}
return s
}
val typeTable = ArrayList<RlMType>()
var firstNullable = -1
fun type(pb: RlPb): RlMType {
var nullable = false; var cls: String? = null
val args = ArrayList<RlMArg>()
pb.each { f, v, s ->
when (f) {
2 -> if (s != null) {
var proj = 2; var t: RlMType? = null
s.each { af, av, asub ->
when (af) {
1 -> proj = av.toInt()
2 -> if (asub != null) t = type(asub)
3 -> t = typeTable.getOrNull(av.toInt())
}
}
args.add(RlMArg(proj, t))
}
3 -> nullable = v != 0L
6 -> cls = str(v.toInt())
}
}
return RlMType(nullable, cls, args)
}
fun tableType(id: Int): RlMType? = typeTable.getOrNull(id)?.let {
if (firstNullable in 0..id && !it.nullable) RlMType(true, it.className, it.args) else it
}
fun param(pb: RlPb): RlMParam {
var flags = 0; var name = "?"; var t: RlMType? = null; var vararg = false
pb.each { f, v, s ->
when (f) {
1 -> flags = v.toInt()
2 -> name = str(v.toInt())
3 -> if (s != null) t = type(s)
5 -> t = tableType(v.toInt())
4, 6 -> vararg = true
}
}
return RlMParam(name, flags and 2 != 0, t, vararg)
}
// Two passes: the type table (field 30) may come after the declarations that use it.
RlPb(bytes, top.p, bytes.size).each { n, _, sub ->
if (n == 30 && sub != null) sub.each { f, v, s ->
if (f == 1 && s != null) typeTable.add(type(s))
if (f == 2) firstNullable = v.toInt()
}
}
var classFlags = 6
val ctors = ArrayList<RlMCtor>(); val props = ArrayList<RlMProp>(); val funs = ArrayList<RlMFun>()
RlPb(bytes, top.p, bytes.size).each { n, v, sub ->
when {
n == 1 -> classFlags = v.toInt()
n == 8 && sub != null -> {
var flags = 6; val ps = ArrayList<RlMParam>()
sub.each { f, fv, s -> if (f == 1) flags = fv.toInt(); if (f == 2 && s != null) ps.add(param(s)) }
ctors.add(RlMCtor(flags and 16 != 0, ps))
}
n == 10 && sub != null -> {
var flags = 518; var name = "?"; var t: RlMType? = null; var ext = false
sub.each { f, fv, s ->
when (f) {
11 -> flags = fv.toInt()
2 -> name = str(fv.toInt())
3 -> if (s != null) t = type(s)
9 -> t = tableType(fv.toInt())
5, 10 -> ext = true
}
}
props.add(RlMProp(name, t, flags, ext))
}
n == 9 && sub != null -> {
var flags = 6; var name = "?"; var t: RlMType? = null; val ps = ArrayList<RlMParam>(); var ext = false
sub.each { f, fv, s ->
when (f) {
9 -> flags = fv.toInt()
2 -> name = str(fv.toInt())
3 -> if (s != null) t = type(s)
7 -> t = tableType(fv.toInt())
6 -> if (s != null) ps.add(param(s))
5, 8 -> ext = true
}
}
funs.add(RlMFun(name, ps, t, flags, ext))
}
}
}
return RlMClass(classFlags, ctors, props, funs)
}
private fun rlErasure(t: java.lang.reflect.Type): Class<*> = when (t) {
is Class<*> -> t
is java.lang.reflect.ParameterizedType -> t.rawType as Class<*>
is java.lang.reflect.WildcardType -> rlErasure(t.upperBounds.firstOrNull() ?: Any::class.java)
is java.lang.reflect.GenericArrayType -> java.lang.reflect.Array.newInstance(rlErasure(t.genericComponentType), 0).javaClass
is java.lang.reflect.TypeVariable<*> -> rlErasure(t.bounds.firstOrNull() ?: Any::class.java)
else -> Any::class.java
}
class RlType(val javaType: java.lang.reflect.Type, val meta: RlMType?, private val forceNullable: Boolean? = null, private val givenArguments: List<kotlin.reflect.KTypeProjection>? = null) : kotlin.reflect.KType {
override val classifier: kotlin.reflect.KClassifier get() = rlErasure(javaType).kotlin
override val isMarkedNullable: Boolean get() = forceNullable ?: meta?.nullable ?: false
override val annotations: List<Annotation> get() = emptyList()
override val arguments: List<kotlin.reflect.KTypeProjection>
get() {
if (givenArguments != null) return givenArguments
val jArgs = (javaType as? java.lang.reflect.ParameterizedType)?.actualTypeArguments
val n = jArgs?.size ?: meta?.args?.size ?: 0
return List(n) { i ->
val ma = meta?.args?.getOrNull(i)
val ja = jArgs?.getOrNull(i)
if (ma?.projection == 3 || (ma == null && ja is java.lang.reflect.WildcardType && ja.lowerBounds.isEmpty() && ja.upperBounds.singleOrNull() == Any::class.java)) {
kotlin.reflect.KTypeProjection.STAR
} else {
val bound = when (ja) {
is java.lang.reflect.WildcardType -> ja.lowerBounds.firstOrNull() ?: ja.upperBounds.firstOrNull() ?: Any::class.java
null -> Any::class.java
else -> ja
}
val t = RlType(bound, ma?.type)
when (ma?.projection) {
0 -> kotlin.reflect.KTypeProjection.contravariant(t)
1 -> kotlin.reflect.KTypeProjection.covariant(t)
else -> kotlin.reflect.KTypeProjection.invariant(t)
}
}
}
}
override fun equals(other: Any?): Boolean = other is kotlin.reflect.KType && classifier == other.classifier &&
arguments == other.arguments && isMarkedNullable == other.isMarkedNullable
override fun hashCode(): Int = (classifier.hashCode() * 31 + arguments.hashCode()) * 31 + (if (isMarkedNullable) 1 else 0)
override fun toString(): String {
val name = meta?.className?.replace('/', '.') ?: (classifier as kotlin.reflect.KClass<*>).qualifiedName ?: rlErasure(javaType).name
val args = arguments.takeIf { it.isNotEmpty() }?.joinToString(", ", "<", ">") ?: ""
return name + args + if (isMarkedNullable) "?" else ""
}
}
class RlParameter(
override val index: Int,
override val name: String?,
override val type: kotlin.reflect.KType,
override val kind: kotlin.reflect.KParameter.Kind,
override val isOptional: Boolean,
override val isVararg: Boolean,
override val annotations: List<Annotation>,
private val callable: Any? = null,
) : kotlin.reflect.KParameter {
override fun equals(other: Any?): Boolean = other is RlParameter && index == other.index && callable == other.callable
override fun hashCode(): Int = index * 31 + callable.hashCode()
override fun toString(): String = when (kind) {
kotlin.reflect.KParameter.Kind.INSTANCE -> "instance parameter"
else -> "parameter #$index $name"
} + " of ..."
}
private fun rlVisibility(mod: Int): kotlin.reflect.KVisibility = when {
java.lang.reflect.Modifier.isPublic(mod) -> kotlin.reflect.KVisibility.PUBLIC
java.lang.reflect.Modifier.isProtected(mod) -> kotlin.reflect.KVisibility.PROTECTED
java.lang.reflect.Modifier.isPrivate(mod) -> kotlin.reflect.KVisibility.PRIVATE
else -> kotlin.reflect.KVisibility.INTERNAL
}
// Like kotlin-reflect, exceptions thrown by the called code arrive wrapped in InvocationTargetException.
private inline fun <R> rlInvoke(block: () -> R): R = block()
private fun rlDefault(c: Class<*>): Any? = when (c) {
java.lang.Boolean.TYPE -> false
java.lang.Character.TYPE -> 0.toChar()
java.lang.Byte.TYPE -> 0.toByte()
java.lang.Short.TYPE -> 0.toShort()
java.lang.Integer.TYPE -> 0
java.lang.Float.TYPE -> 0f
java.lang.Long.TYPE -> 0L
java.lang.Double.TYPE -> 0.0
else -> null
}
abstract class RlCallable<R> : kotlin.reflect.KCallable<R> {
var accessible: Boolean = false
override val typeParameters: List<kotlin.reflect.KTypeParameter> get() = emptyList()
override val isSuspend: Boolean get() = false
override val isFinal: Boolean get() = true
override val isOpen: Boolean get() = false
override val isAbstract: Boolean get() = false
protected fun checkAccess(member: java.lang.reflect.AccessibleObject, mod: Int) {
if (!java.lang.reflect.Modifier.isPublic(mod)) {
if (!accessible) throw IllegalStateException("Class can not access a member with modifiers \"${java.lang.reflect.Modifier.toString(mod)}\". Set isAccessible = true first.")
member.isAccessible = true
} else {
runCatching { member.isAccessible = true }
}
}
}
/** A constructor or a member function. */
class RlFunction<R>(
private val owner: Class<*>,
val javaConstructor: java.lang.reflect.Constructor<*>?,
val javaMethod: java.lang.reflect.Method?,
private val metaParams: List<RlMParam>?,
private val metaReturn: RlMType?,
private val suspendFlag: Boolean = false,
) : RlCallable<R>(), kotlin.reflect.KFunction<R> {
private val exec: java.lang.reflect.Executable get() = javaConstructor ?: javaMethod!!
override val name: String get() = javaMethod?.name ?: "<init>"
override val isInline: Boolean get() = false
override val isExternal: Boolean get() = false
override val isOperator: Boolean get() = false
override val isInfix: Boolean get() = false
override val isSuspend: Boolean get() = suspendFlag
override val isFinal: Boolean get() = java.lang.reflect.Modifier.isFinal(exec.modifiers) || javaConstructor != null
override val isOpen: Boolean get() = !isFinal && !isAbstract
override val isAbstract: Boolean get() = java.lang.reflect.Modifier.isAbstract(exec.modifiers)
override val visibility: kotlin.reflect.KVisibility get() = rlVisibility(exec.modifiers)
override val annotations: List<Annotation> get() = exec.annotations.toList()
override val returnType: kotlin.reflect.KType
get() = if (javaConstructor != null) RlType(owner, null) else RlType(javaMethod!!.genericReturnType, metaReturn)
private val hasInstance: Boolean get() = javaMethod != null && !java.lang.reflect.Modifier.isStatic(javaMethod.modifiers)
override val parameters: List<kotlin.reflect.KParameter> by lazy {
val types = exec.genericParameterTypes
val annotations = exec.parameterAnnotations
val instance = if (hasInstance) listOf(RlParameter(0, null, RlType(owner, null), kotlin.reflect.KParameter.Kind.INSTANCE, false, false, emptyList(), exec)) else emptyList()
instance + List(metaParams?.size ?: types.size) { i ->
val mp = metaParams?.getOrNull(i)
RlParameter(i + instance.size, mp?.name ?: "arg$i", RlType(types[i], mp?.type), kotlin.reflect.KParameter.Kind.VALUE, mp?.optional ?: false, mp?.isVararg ?: false, annotations.getOrNull(i)?.toList() ?: emptyList(), exec)
}
}
@Suppress("UNCHECKED_CAST")
override fun call(vararg args: Any?): R = rlInvoke {
checkAccess(exec, exec.modifiers)
if (javaConstructor != null) javaConstructor.newInstance(*args) as R
else if (hasInstance) javaMethod!!.invoke(args[0], *args.drop(1).toTypedArray()) as R
else javaMethod!!.invoke(null, *args) as R
}
@Suppress("UNCHECKED_CAST")
override fun callBy(args: Map<kotlin.reflect.KParameter, Any?>): R {
val missing = parameters.filter { it !in args }
missing.firstOrNull { !it.isOptional }?.let { throw IllegalArgumentException("No argument provided for a required parameter: $it") }
if (missing.isEmpty()) return call(*parameters.map { args[it] }.toTypedArray())
val values = parameters.filter { it.kind == kotlin.reflect.KParameter.Kind.VALUE }
val types = exec.parameterTypes
val masks = IntArray((values.size + 31) / 32)
val actual = values.mapIndexed { i, p ->
if (p in args) args[p] else { masks[i / 32] = masks[i / 32] or (1 shl (i % 32)); rlDefault(types[i]) }
}
return rlInvoke {
if (javaConstructor != null) {
val synthetic = owner.declaredConstructors.firstOrNull {
it.parameterCount == types.size + masks.size + 1 && it.parameterTypes.take(types.size) == types.toList() &&
it.parameterTypes.last().name == "kotlin.jvm.internal.DefaultConstructorMarker"
} ?: throw UnsupportedOperationException("reflect-lite: no constructor with default arguments found in ${owner.name}")
synthetic.isAccessible = true
synthetic.newInstance(*(actual + masks.toList() + listOf(null)).toTypedArray()) as R
} else {
val instance = if (hasInstance) listOf(args[parameters[0]]) else emptyList()
val synthetic = owner.declaredMethods.firstOrNull {
it.name == javaMethod!!.name + "\$default" && it.parameterCount == instance.size + types.size + masks.size + 1
} ?: throw UnsupportedOperationException("reflect-lite: no function with default arguments found for ${javaMethod!!.name}")
synthetic.isAccessible = true
synthetic.invoke(null, *(instance + actual + masks.toList() + listOf(null)).toTypedArray()) as R
}
}
}
override fun equals(other: Any?): Boolean = other is RlFunction<*> && exec == other.exec
override fun hashCode(): Int = exec.hashCode()
override fun toString(): String {
val ps = parameters.filter { it.kind == kotlin.reflect.KParameter.Kind.VALUE }.joinToString(", ") { it.type.toString() }
val receiver = if (hasInstance) "${owner.kotlin.qualifiedName ?: owner.name}." else ""
return if (javaConstructor != null) "fun `<init>`($ps): $returnType" else "fun $receiver$name($ps): $returnType"
}
}
open class RlProperty<T, V>(
val owner: Class<*>,
val meta: RlMProp,
val javaGetter: java.lang.reflect.Method?,
val javaSetter: java.lang.reflect.Method?,
val javaField: java.lang.reflect.Field?,
) : RlCallable<V>(), kotlin.reflect.KProperty1<T, V> {
var displayOwner: Class<*> = owner
override val name: String get() = meta.name
override val isLateinit: Boolean get() = meta.flags and (1 shl 12) != 0
override val isConst: Boolean get() = meta.flags and (1 shl 11) != 0
override val isFinal: Boolean get() = javaGetter?.let { java.lang.reflect.Modifier.isFinal(it.modifiers) } ?: true
override val isOpen: Boolean get() = !isFinal && !isAbstract
override val isAbstract: Boolean get() = javaGetter?.let { java.lang.reflect.Modifier.isAbstract(it.modifiers) } ?: false
override val visibility: kotlin.reflect.KVisibility
get() = rlVisibility(javaGetter?.modifiers ?: javaField?.modifiers ?: java.lang.reflect.Modifier.PRIVATE)
override val returnType: kotlin.reflect.KType
get() = RlType(javaGetter?.genericReturnType ?: javaField?.genericType ?: Any::class.java, meta.type)
override val parameters: List<kotlin.reflect.KParameter>
get() = listOf(RlParameter(0, null, RlType(owner, null), kotlin.reflect.KParameter.Kind.INSTANCE, false, false, emptyList(), this))
override val annotations: List<Annotation>
get() {
val getterName = if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) name else "get" + name.replaceFirstChar { it.uppercaseChar() }
val holder = owner.declaredMethods.firstOrNull { it.name == "$getterName\$annotations" }
return holder?.annotations?.filter { it.annotationClass != Deprecated::class && it.annotationClass.java != java.lang.Deprecated::class.java } ?: emptyList()
}
@Suppress("UNCHECKED_CAST")
override fun get(receiver: T): V = rlInvoke {
if (javaGetter != null) { checkAccess(javaGetter, javaGetter.modifiers); javaGetter.invoke(receiver) as V }
else { val f = javaField ?: throw UnsupportedOperationException("reflect-lite: property $name has no getter and no field"); checkAccess(f, f.modifiers); f.get(receiver) as V }
}
override fun invoke(p1: T): V = get(p1)
@Suppress("UNCHECKED_CAST")
override fun call(vararg args: Any?): V = get(args[0] as T)
@Suppress("UNCHECKED_CAST")
override fun callBy(args: Map<kotlin.reflect.KParameter, Any?>): V = get(args.values.single() as T)
override fun getDelegate(receiver: T): Any? = throw UnsupportedOperationException("reflect-lite: getDelegate is not supported")
override val getter: kotlin.reflect.KProperty1.Getter<T, V>
get() = throw UnsupportedOperationException("reflect-lite: property accessors are not supported, use get/set")
override fun equals(other: Any?): Boolean = other is RlProperty<*, *> && owner == other.owner && name == other.name
override fun hashCode(): Int = owner.hashCode() * 31 + name.hashCode()
override fun toString(): String = "${if (this is kotlin.reflect.KMutableProperty<*>) "var" else "val"} ${displayOwner.kotlin.qualifiedName ?: displayOwner.name}.$name: $returnType"
}
class RlMutableProperty<T, V>(owner: Class<*>, meta: RlMProp, g: java.lang.reflect.Method?, s: java.lang.reflect.Method?, f: java.lang.reflect.Field?) :
RlProperty<T, V>(owner, meta, g, s, f), kotlin.reflect.KMutableProperty1<T, V> {
override fun set(receiver: T, value: V) {
rlInvoke {
if (javaSetter != null) { checkAccess(javaSetter, javaSetter.modifiers); javaSetter.invoke(receiver, value) }
else { val f = javaField ?: throw UnsupportedOperationException("reflect-lite: property $name has no setter and no field"); checkAccess(f, f.modifiers); f.set(receiver, value) }
}
}
override val setter: kotlin.reflect.KMutableProperty1.Setter<T, V>
get() = throw UnsupportedOperationException("reflect-lite: property accessors are not supported, use get/set")
}
private fun rlGetterName(name: String): String =
if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) name else "get" + name.replaceFirstChar { it.uppercaseChar() }
private fun rlSetterName(name: String): String =
"set" + (if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) name.substring(2) else name.replaceFirstChar { it.uppercaseChar() })
private val rlPropertyCache = java.util.concurrent.ConcurrentHashMap<Class<*>, List<kotlin.reflect.KProperty1<*, *>>>()
// Cached, so that isAccessible set on a property is remembered, as in kotlin-reflect.
@Suppress("UNCHECKED_CAST")
private fun <T : Any> rlDeclaredProperties(c: Class<*>): List<kotlin.reflect.KProperty1<T, *>> =
rlPropertyCache.getOrPut(c) { rlReadProperties<Any>(c) } as List<kotlin.reflect.KProperty1<T, *>>
private fun <T : Any> rlReadProperties(c: Class<*>): List<kotlin.reflect.KProperty1<T, *>> {
val meta = rlMeta(c) ?: return emptyList()
return meta.props.filter { !it.isExtension }.sortedBy { it.name }.map { p ->
val getter = c.declaredMethods.firstOrNull { it.name.substringBefore('-') == rlGetterName(p.name) && it.parameterCount == 0 && !it.isSynthetic }
val setter = c.declaredMethods.firstOrNull { it.name.substringBefore('-') == rlSetterName(p.name) && it.parameterCount == 1 && !it.isSynthetic }
val field = runCatching { c.getDeclaredField(p.name) }.getOrNull() ?: runCatching { c.getDeclaredField(p.name + "\$delegate") }.getOrNull()
if (p.flags and (1 shl 8) != 0) RlMutableProperty<T, Any?>(c, p, getter, setter, field) else RlProperty<T, Any?>(c, p, getter, setter, field)
}
}
private fun rlSupers(c: Class<*>): List<Class<*>> = buildList {
fun visit(x: Class<*>) { if (x !in this) { add(x); x.superclass?.let(::visit); x.interfaces.forEach(::visit) } }
visit(c)
}
val <T : Any> kotlin.reflect.KClass<T>.declaredMemberProperties: Collection<kotlin.reflect.KProperty1<T, *>>
get() = rlDeclaredProperties(java)
val <T : Any> kotlin.reflect.KClass<T>.memberProperties: Collection<kotlin.reflect.KProperty1<T, *>>
get() {
val seen = HashSet<String>()
return rlSupers(java).flatMap { rlDeclaredProperties<T>(it) }
.filter { it.visibility != kotlin.reflect.KVisibility.PRIVATE || (it as RlProperty<*, *>).owner == java }
.filter { seen.add(it.name) }
}
private fun rlDeclaredFunctions(c: Class<*>): List<kotlin.reflect.KFunction<*>> {
val meta = rlMeta(c) ?: return emptyList()
return meta.funs.filter { !it.isExtension }.sortedBy { it.name }.mapNotNull { f ->
val suspend = f.flags and (1 shl 14) != 0
val count = f.params.size + if (suspend) 1 else 0
val m = c.declaredMethods.firstOrNull { it.name.substringBefore('-') == f.name && it.parameterCount == count && !it.isSynthetic && !java.lang.reflect.Modifier.isStatic(it.modifiers) }
m?.let { RlFunction<Any?>(c, null, it, f.params, f.ret, suspend) }
}
}
val kotlin.reflect.KClass<*>.declaredMemberFunctions: Collection<kotlin.reflect.KFunction<*>> get() = rlDeclaredFunctions(java)
val kotlin.reflect.KClass<*>.memberFunctions: Collection<kotlin.reflect.KFunction<*>>
get() {
val seen = HashSet<String>()
val own = rlSupers(java).filter { it != Any::class.java }.flatMap { rlDeclaredFunctions(it) }
.filter { seen.add(it.name + (it as RlFunction<*>).javaMethod!!.parameterTypes.joinToString { p -> p.name }) }
val any = listOf("equals", "hashCode", "toString").filter { n -> own.none { it.name == n } }.map { n ->
val m = Any::class.java.declaredMethods.first { it.name == n }
val ps = if (n == "equals") listOf(RlMParam("other", false, RlMType(true, "kotlin/Any", emptyList()), false)) else emptyList()
RlFunction<Any?>(Any::class.java, null, m, ps, null)
}
return own + any
}
val <T : Any> kotlin.reflect.KClass<T>.primaryConstructor: kotlin.reflect.KFunction<T>?
get() {
val meta = rlMeta(java) ?: return null
val primary = meta.ctors.firstOrNull { !it.secondary } ?: return null
val candidates = java.declaredConstructors.filter { !it.isSynthetic && it.parameterCount == primary.params.size }
val ctor = candidates.singleOrNull() ?: candidates.firstOrNull() ?: return null
return RlFunction(java, ctor, null, primary.params, null)
}
@Suppress("UNCHECKED_CAST")
fun <T : Any> kotlin.reflect.KClass<T>.createInstance(): T {
val noArg = java.declaredConstructors.firstOrNull { it.parameterCount == 0 }
if (noArg != null) return rlInvoke { noArg.isAccessible = true; noArg.newInstance() as T }
val primary = primaryConstructor?.takeIf { c -> c.parameters.all { it.isOptional } }
?: throw IllegalArgumentException("Class should have a single no-arg constructor: $this")
return primary.callBy(emptyMap())
}
fun rlAnnotations(e: kotlin.reflect.KAnnotatedElement): List<Annotation> = when (e) {
is kotlin.reflect.KClass<*> -> e.java.annotations.filter { it !is Metadata }
is RlCallable<*>, is RlParameter, is RlType -> e.annotations
is kotlin.jvm.internal.CallableReference -> rlLite(e)?.annotations ?: emptyList()
else -> e.annotations
}
inline fun <reified A : Annotation> kotlin.reflect.KAnnotatedElement.findAnnotation(): A? =
rlAnnotations(this).filterIsInstance<A>().firstOrNull()
inline fun <reified A : Annotation> kotlin.reflect.KAnnotatedElement.findAnnotations(): List<A> =
rlAnnotations(this).filterIsInstance<A>()
inline fun <reified A : Annotation> kotlin.reflect.KAnnotatedElement.hasAnnotation(): Boolean = findAnnotation<A>() != null
/** The reflect-lite counterpart of a callable reference such as `User::name`, or null. */
fun rlLite(ref: kotlin.jvm.internal.CallableReference): RlCallable<*>? {
val ownerClass = (ref.owner as? kotlin.reflect.KClass<*>)?.java ?: return null
return when (ref) {
is kotlin.reflect.KProperty<*> -> rlSupers(ownerClass).flatMap { rlDeclaredProperties<Any>(it) }.firstOrNull { it.name == ref.name } as RlCallable<*>?
is kotlin.reflect.KFunction<*> ->
if (ref.name == "<init>") ownerClass.kotlin.primaryConstructor as RlCallable<*>?
else ownerClass.kotlin.memberFunctions.firstOrNull { it.name == ref.name } as RlCallable<*>?
else -> null
}
}
var <T> kotlin.reflect.KCallable<T>.isAccessible: Boolean
get() = (this as? RlCallable<*>)?.accessible ?: true
set(value) {
(this as? RlCallable<*> ?: throw UnsupportedOperationException("reflect-lite: isAccessible works only on members obtained from memberProperties, memberFunctions or primaryConstructor")).accessible = value
}
val kotlin.reflect.KType.jvmErasure: kotlin.reflect.KClass<*>
get() = classifier as? kotlin.reflect.KClass<*> ?: Any::class
fun kotlin.reflect.KType.withNullability(nullable: Boolean): kotlin.reflect.KType = when (this) {
is RlType -> RlType(javaType, meta, nullable, arguments)
else -> if (isMarkedNullable == nullable) this else RlType((classifier as kotlin.reflect.KClass<*>).javaObjectType, null, nullable, arguments)
}
val kotlin.reflect.KClass<*>.superclasses: List<kotlin.reflect.KClass<*>>
get() = (listOfNotNull(java.superclass) + java.interfaces).map { it.kotlin }.ifEmpty { if (java == Any::class.java) emptyList() else listOf(Any::class) }
val kotlin.reflect.KClass<*>.allSuperclasses: Collection<kotlin.reflect.KClass<*>>
get() = rlSupers(java).drop(1).map { it.kotlin }
fun kotlin.reflect.KClass<*>.isSubclassOf(base: kotlin.reflect.KClass<*>): Boolean = base.javaObjectType.isAssignableFrom(javaObjectType)
fun kotlin.reflect.KClass<*>.isSuperclassOf(derived: kotlin.reflect.KClass<*>): Boolean = derived.isSubclassOf(this)
private fun rlCompanion(c: Class<*>): Any? =
c.declaredFields.firstOrNull { java.lang.reflect.Modifier.isStatic(it.modifiers) && it.type.enclosingClass == c && it.type.simpleName == it.name }
?.let { it.isAccessible = true; it.get(null) }
val kotlin.reflect.KClass<*>.companionObjectInstance: Any? get() = rlCompanion(java)
val kotlin.reflect.KClass<*>.companionObject: kotlin.reflect.KClass<*>? get() = companionObjectInstance?.let { it::class }
val kotlin.reflect.KProperty<*>.javaField: java.lang.reflect.Field?
get() = ((this as? RlProperty<*, *>) ?: (this as? kotlin.jvm.internal.CallableReference)?.let { rlLite(it) } as? RlProperty<*, *>)?.javaField
val kotlin.reflect.KProperty<*>.javaGetter: java.lang.reflect.Method?
get() = ((this as? RlProperty<*, *>) ?: (this as? kotlin.jvm.internal.CallableReference)?.let { rlLite(it) } as? RlProperty<*, *>)?.javaGetter
val kotlin.reflect.KFunction<*>.javaMethod: java.lang.reflect.Method? get() = (this as? RlFunction<*>)?.javaMethod
val <T> kotlin.reflect.KFunction<T>.javaConstructor: java.lang.reflect.Constructor<*>? get() = (this as? RlFunction<*>)?.javaConstructor
val kotlin.reflect.KClass<*>.functions: Collection<kotlin.reflect.KFunction<*>> get() = memberFunctions
val kotlin.reflect.KClass<*>.declaredFunctions: Collection<kotlin.reflect.KFunction<*>> get() = declaredMemberFunctions
val kotlin.reflect.KClass<*>.declaredMembers: Collection<kotlin.reflect.KCallable<*>> get() = declaredMemberFunctions + declaredMemberProperties
/** A member extension property: only its name, type and value are supported. */
class RlProperty2<D, E, V>(private val owner: Class<*>, private val meta: RlMProp, private val javaGetter: java.lang.reflect.Method?) :
RlCallable<V>(), kotlin.reflect.KProperty2<D, E, V> {
override val name: String get() = meta.name
override val isLateinit: Boolean get() = false
override val isConst: Boolean get() = false
override val visibility: kotlin.reflect.KVisibility get() = rlVisibility(javaGetter?.modifiers ?: java.lang.reflect.Modifier.PRIVATE)
override val returnType: kotlin.reflect.KType get() = RlType(javaGetter?.genericReturnType ?: Any::class.java, meta.type)
override val annotations: List<Annotation> get() = emptyList()
override val parameters: List<kotlin.reflect.KParameter>
get() = listOf(
RlParameter(0, null, RlType(owner, null), kotlin.reflect.KParameter.Kind.INSTANCE, false, false, emptyList(), this),
RlParameter(1, null, RlType(javaGetter?.genericParameterTypes?.firstOrNull() ?: Any::class.java, null), kotlin.reflect.KParameter.Kind.EXTENSION_RECEIVER, false, false, emptyList(), this),
)
@Suppress("UNCHECKED_CAST")
override fun get(receiver1: D, receiver2: E): V {
val g = javaGetter ?: throw UnsupportedOperationException("reflect-lite: property $name has no getter")
checkAccess(g, g.modifiers)
return g.invoke(receiver1, receiver2) as V
}
override fun invoke(p1: D, p2: E): V = get(p1, p2)
@Suppress("UNCHECKED_CAST")
override fun call(vararg args: Any?): V = get(args[0] as D, args[1] as E)
@Suppress("UNCHECKED_CAST")
override fun callBy(args: Map<kotlin.reflect.KParameter, Any?>): V = get(args[parameters[0]] as D, args[parameters[1]] as E)
override fun getDelegate(receiver1: D, receiver2: E): Any? = throw UnsupportedOperationException("reflect-lite: getDelegate is not supported")
override val getter: kotlin.reflect.KProperty2.Getter<D, E, V>
get() = throw UnsupportedOperationException("reflect-lite: property accessors are not supported, use get")
override fun toString(): String = "val ${owner.kotlin.qualifiedName ?: owner.name}.(${parameters[1].type}.)$name: $returnType"
}
private fun <T : Any> rlExtensionProperties(c: Class<*>): List<kotlin.reflect.KProperty2<T, *, *>> {
val meta = rlMeta(c) ?: return emptyList()
return meta.props.filter { it.isExtension }.sortedBy { it.name }.map { p ->
RlProperty2<T, Any?, Any?>(c, p, c.declaredMethods.firstOrNull { it.name == rlGetterName(p.name) && it.parameterCount == 1 && !it.isSynthetic })
}
}
val <T : Any> kotlin.reflect.KClass<T>.declaredMemberExtensionProperties: Collection<kotlin.reflect.KProperty2<T, *, *>>
get() = rlExtensionProperties(java)
val <T : Any> kotlin.reflect.KClass<T>.memberExtensionProperties: Collection<kotlin.reflect.KProperty2<T, *, *>>
get() = rlSupers(java).flatMap { rlExtensionProperties<T>(it) }.distinctBy { it.name }
/** An approximation: compares classes and nullability; type arguments must be equal or star-projected. */
fun kotlin.reflect.KType.isSubtypeOf(other: kotlin.reflect.KType): Boolean {
if (isMarkedNullable && !other.isMarkedNullable) return false
val mine = classifier as? kotlin.reflect.KClass<*> ?: return false
val theirs = other.classifier as? kotlin.reflect.KClass<*> ?: return false
if (!theirs.javaObjectType.isAssignableFrom(mine.javaObjectType)) return false
if (mine != theirs || other.arguments.isEmpty()) return true
return arguments.size == other.arguments.size && arguments.zip(other.arguments).all { (a, b) ->
val at = a.type
val bt = b.type
bt == null || (at != null && when (b.variance) {
kotlin.reflect.KVariance.OUT -> at.isSubtypeOf(bt)
kotlin.reflect.KVariance.IN -> bt.isSubtypeOf(at)
else -> at == bt || bt == at
})
}
}
fun kotlin.reflect.KType.isSupertypeOf(other: kotlin.reflect.KType): Boolean = other.isSubtypeOf(this)
val java.lang.reflect.Field.kotlinProperty: kotlin.reflect.KProperty<*>?
get() = declaringClass.kotlin.declaredMemberProperties.firstOrNull { (it as RlProperty<*, *>).javaField == this }
val java.lang.reflect.Method.kotlinFunction: kotlin.reflect.KFunction<*>?
get() = declaringClass.kotlin.declaredMemberFunctions.firstOrNull { (it as RlFunction<*>).javaMethod == this }
val <T : Any> java.lang.reflect.Constructor<T>.kotlinFunction: kotlin.reflect.KFunction<T>?
get() = declaringClass.kotlin.primaryConstructor?.takeIf { (it as RlFunction<*>).javaConstructor == this }
val kotlin.reflect.KProperty<*>.javaSetter: java.lang.reflect.Method?
get() = ((this as? RlProperty<*, *>) ?: (this as? kotlin.jvm.internal.CallableReference)?.let { rlLite(it) } as? RlProperty<*, *>)?.javaSetter
// ===== end of reflect-lite =====
The KProperty type has a few property-specific properties:
isLateinit: Boolean - true if this property is lateinit.
isConst: Boolean - true if this property is const.
getter: Getter<V> - a reference to an object representing a property getter.
KMutableProperty only adds a single property:
setter: Setter<V> - a reference to an object representing a property setter.
Types representing properties with a specific number of receivers additionally provide this property getter’s get function, and mutable variants also provide the set function for this property setter. Both get and set have an appropriate number of additional parameters for receivers. For instance, in KMutableProperty1, the get function expects a single argument for the receiver, and set expects one argument for the receiver and one for a value. Additionally, more specific types that represent properties provide more specific references to getters and setters.
import kotlin.reflect.*
class Box(
var value: Int = 0
)
fun main() {
val box = Box()
val p: KMutableProperty1<Box, Int> = Box::value
println(p.get(box)) // 0
p.set(box, 999)
println(p.get(box)) // 999
}
In the next part, we’ll cover class references and show how to implement object serialization. See you then!
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.
Owen has been developing software since the mid 1990s and remembers the productivity of languages such as Clipper and Borland Delphi.
Since 2001, He moved to Web, Server based Java and the Open Source revolution.
With many years of commercial Java experience, He picked up on Kotlin in early 2015.
After taking detours into Clojure and Scala, like Goldilocks, He thinks Kotlin is just right and tastes the best.
Owen enthusiastically helps Kotlin developers continue to succeed.