
class keyword. The result is KClass<T>, where T is the type representing a class.import kotlin.reflect.KClass class A fun main() { val class1: KClass<A> = A::class println(class1) // class A val a: A = A() val class2: KClass<out A> = a::class println(class2) // class A }
A might contain an object of type A or any of its subtypes.import kotlin.reflect.KClass open class A class B : A() fun main() { val a: A = B() val clazz: KClass<out A> = a::class println(clazz) // class B }
Sinceclassis a reserved keyword in Kotlin and cannot be used as the variable name, it is a popular practice to use "clazz" instead.
- Simple name is just the name used after the
classkeyword. We can read it using thesimpleNameproperty. - The fully qualified name is the name that includes the package and the enclosing classes. We can read it using the
qualifiedNameproperty.
package a.b.c class D { class E } fun main() { val clazz = D.E::class println(clazz.simpleName) // E println(clazz.qualifiedName) // a.b.c.D.E }
simpleName and qualifiedName return null when we reference an object expression or any other nameless object.fun main() { val o = object {} val clazz = o::class println(clazz.simpleName) // null println(clazz.qualifiedName) // null }
KClass has only a few properties that let us check some class-specific characteristics:isFinal: Boolean-trueif this class isfinal.isOpen: Boolean-trueif this class has theopenmodifier. Abstract and sealed classes, even though they are generally considered abstract, will returnfalse.isAbstract: Boolean-trueif this class has theabstractmodifier. Sealed classes, even though they are generally considered abstract, will returnfalse.isSealed: Boolean-trueif this class has thesealedmodifier.isData: Boolean-trueif this class has thedatamodifier.isInner: Boolean-trueif this class has theinnermodifier.isCompanion: Boolean-trueif this class is a companion object.isFun: Boolean-trueif this class is a Kotlin functional interface and so has thefunmodifier.isValue: Boolean-trueif this class is a value class and so has thevaluemodifier.
visibility property.sealed class UserMessages private data class UserId(val id: String) { companion object { val ZERO = UserId("") } } internal fun interface Filter<T> { fun check(value: T): Boolean } fun main() { println(UserMessages::class.visibility) // PUBLIC println(UserMessages::class.isSealed) // true println(UserMessages::class.isOpen) // false println(UserMessages::class.isFinal) // false println(UserMessages::class.isAbstract) // false println(UserId::class.visibility) // PRIVATE println(UserId::class.isData) // true println(UserId::class.isFinal) // true println(UserId.Companion::class.isCompanion) // true println(UserId.Companion::class.isInner) // false println(Filter::class.visibility) // INTERNAL println(Filter::class.isFun) // true }
members: Collection<KCallable<*>>- returns all class members, including those declared by parents of this class.functions: Collection<KFunction<*>>- returns all class member functions, including those declared by parents of this class.memberProperties: Collection<KProperty1<*>>- returns all class member properties, including those declared by parents of this class.declaredMembers: Collection<KCallable<*>>- returns members declared by this class.declaredFunctions: Collection<KFunction<*>>- returns functions declared by this class.declaredMemberProperties: Collection<KProperty1<*>>- returns member properties declared by this class.
//sampleStart // import kotlin.reflect.full.* // replaced by reflect-lite open class Parent { val a = 12 fun b() {} } class Child : Parent() { val c = 12 fun d() {} } fun Child.e() {} fun main() { println(Child::class.members.map { it.name }) // [c, d, a, b, equals, hashCode, toString] println(Child::class.functions.map { it.name }) // [d, b, equals, hashCode, toString] println(Child::class.memberProperties.map { it.name }) // [c, a] println(Child::class.declaredMembers.map { it.name }) // [c, d] println(Child::class.declaredFunctions.map { it.name }) // [d] println(Child::class.declaredMemberProperties.map { it.name }) // [c] } //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 =====
constructors property.package playground import kotlin.reflect.KFunction class User(val name: String) { constructor(user: User) : this(user.name) constructor(json: UserJson) : this(json.name) } class UserJson(val name: String) fun main() { val constructors: Collection<KFunction<User>> = User::class.constructors println(constructors.size) // 3 constructors.forEach(::println) // fun <init>(playground.User): playground.User // fun <init>(playground.UserJson): playground.User // fun <init>(kotlin.String): playground.User }
superclasses property, which returns List<KClass<*>>. In reflection API nomenclature, remember that interfaces are also considered classes, so their references are of type KClass and they are returned by the superclasses property. We can also get the types of the same direct superclass and directly implemented interfaces using the supertypes property, which returns List<KType>. This property actually returns a list of superclasses, not supertypes, as it doesn’t include nullable types, but it includes Any if there is no other direct superclass.//sampleStart import kotlin.reflect.KClass // import kotlin.reflect.full.superclasses // replaced by reflect-lite interface I1 interface I2 open class A : I1 class B : A(), I2 fun main() { val a = A::class val b = B::class println(a.superclasses) // [class I1, class kotlin.Any] println(b.superclasses) // [class A, class I2] println(a.supertypes) // [I1, kotlin.Any] println(b.supertypes) // [A, I2] } //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 =====
interface I1 interface I2 open class A : I1 class B : A(), I2 fun main() { val a = A() val b = B() println(A::class.isInstance(a)) // true println(B::class.isInstance(a)) // false println(I1::class.isInstance(a)) // true println(I2::class.isInstance(a)) // false println(A::class.isInstance(b)) // true println(B::class.isInstance(b)) // true println(I1::class.isInstance(b)) // true println(I2::class.isInstance(b)) // true }
KTypeParameter type. We can get a list of all type parameters defined by a class using the typeParameters property.fun main() { println(List::class.typeParameters) // [out E] println(Map::class.typeParameters) // [K, out V] }
nestedClasses property.class A { class B inner class C } fun main() { println(A::class.nestedClasses) // [class A$B, class A$C] }
sealedSubclasses: List<KClass<out T>>.sealed class LinkedList<out T> class Node<out T>( val head: T, val next: LinkedList<T> ) : LinkedList<T>() object Empty : LinkedList<Nothing>() fun main() { println(LinkedList::class.sealedSubclasses) // [class Node, class Empty] }
objectInstance property of type T?, where T is the KClass type parameter. This property returns null when a class does not represent an object declaration.import kotlin.reflect.KClass sealed class LinkedList<out T> data class Node<out T>( val head: T, val next: LinkedList<T> ) : LinkedList<T>() data object Empty : LinkedList<Nothing>() fun main() { println(Node::class.objectInstance) // null println(Empty::class.objectInstance) // Empty }
toJson function which will serialize objects into JSON format.class Creature( val name: String, val attack: Int, val defence: Int, ) fun main() { val creature = Creature( name = "Cockatrice", attack = 2, defence = 4 ) println(creature.toJson()) // {"attack": 2, "defence": 4, "name": "Cockatrice"} }
toJson, I will define a couple of helper functions, starting with objectToJson, which is responsible for serializing objects to JSON and assumes that its argument is an object. Objects in JSON format are surrounded by curly braces containing property-value pairs separated with commas. In each pair, first there is a property name in quotes, then a colon, and then a serialized value. To implement objectToJson, we first need to have a list of object properties. For that, we will reference this object, and then we can either use memberProperties (including all properties in this object, including those inherited from the parent) or declaredMemberProperties (including properties declared by the class constructing this object). Once we have a list of properties, we can use joinToString to create a string with property-value pairs. We specify prefix and postfix parameters to surround the result string with curly brackets. We also define transform tospecify how property-value pairs should be transformed to a string. Inside them, we take property names using the
name property; we get property value by calling the call method from this property reference, and we then transform the result value to a string using the valueToJson function.fun Any.toJson(): String = objectToJson(this) private fun objectToJson(any: Any) = any::class .memberProperties .joinToString( prefix = "{", postfix = "}", transform = { prop -> "\"${prop.name}\": ${valueToJson(prop.call(any))}" } )
valueToJson function to serialize JSON values. JSON format supports a number of values, but most of them can just be serialized using the Kotlin string template. This includes the null value, all numbers, and enums. An important exception is strings, which need to be additionally wrapped with quotes1In fact, strings are much harder to serialize because special characters need to be escaped so as not to mess with the JSON format, but I will ignore this to keep this example simple.. All non-basic types will be treated as objects and serialized with the objectToJson function.private fun valueToJson(value: Any?): String = when (value) { null, is Number -> "$value" is String, is Enum<*> -> "\"$value\"" // ... else -> objectToJson(value) }
//sampleStart // import kotlin.reflect.full.memberProperties // replaced by reflect-lite // Serialization function definition fun Any.toJson(): String = objectToJson(this) private fun objectToJson(any: Any) = any::class .memberProperties .joinToString( prefix = "{", postfix = "}", transform = { prop -> "\"${prop.name}\": ${valueToJson(prop.call(any))}" } ) private fun valueToJson(value: Any?): String = when (value) { null, is Number, is Boolean -> "$value" is String, is Enum<*> -> "\"$value\"" is Iterable<*> -> iterableToJson(value) is Map<*, *> -> mapToJson(value) else -> objectToJson(value) } private fun iterableToJson(any: Iterable<*>): String = any .joinToString( prefix = "[", postfix = "]", transform = ::valueToJson ) private fun mapToJson(any: Map<*, *>) = any.toList() .joinToString( prefix = "{", postfix = "}", transform = { "\"${it.first}\": ${valueToJson(it.second)}" } ) // Example use class Creature( val name: String, val attack: Int, val defence: Int, val traits: List<Trait>, val cost: Map<Element, Int> ) enum class Element { FOREST, ANY, } enum class Trait { FLYING } fun main() { val creature = Creature( name = "Cockatrice", attack = 2, defence = 4, traits = listOf(Trait.FLYING), cost = mapOf( Element.ANY to 3, Element.FOREST to 2 ) ) println(creature.toJson()) // {"attack": 2, "cost": {"ANY": 3, "FOREST": 2}, // "defence": 4, "name": "Cockatrice", // "traits": ["FLYING"]} } //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 =====
JsonName annotation, which should set a different name for the serialized form, and JsonIgnore, which should make the serializer ignore the annotated property.// Annotations @Target(AnnotationTarget.PROPERTY) annotation class JsonName(val name: String) @Target(AnnotationTarget.PROPERTY) annotation class JsonIgnore // Example use class Creature( @JsonIgnore val name: String, @JsonName("att") val attack: Int, @JsonName("def") val defence: Int, val traits: List<Trait>, val cost: Map<Element, Int> ) enum class Element { FOREST, ANY, } enum class Trait { FLYING } fun main() { val creature = Creature( name = "Cockatrice", attack = 2, defence = 4, traits = listOf(Trait.FLYING), cost = mapOf( Element.ANY to 3, Element.FOREST to 2 ) ) println(creature.toJson()) // {"att": 2, "cost": {"ANY": 3, "FOREST": 2}, // "def": 4, "traits": ["FLYING"]} }
objectToJson function. To ignore properties, we will add a filter on the properties list. For each property, we need to check if it has the JsonIgnore annotation. To check if a property has this annotation, we could use the annotations property, but we can also use the hasAnnotation extension function on KAnnotatedElement. To respect a name change, we need to find the JsonName property annotation by using the findAnnotation extension function on KAnnotatedElement. This is how our function needs to be modified to respect both annotations:private fun objectToJson(any: Any) = any::class .memberProperties .filterNot { it.hasAnnotation<JsonIgnore>() } .joinToString( prefix = "{", postfix = "}", transform = { prop -> val annotation = prop.findAnnotation<JsonName>() val name = annotation?.name ?: prop.name "\"${name}\": ${valueToJson(prop.call(any))}" } )
- 1.In fact, strings are much harder to serialize because special characters need to be escaped so as not to mess with the JSON format, but I will ignore this to keep this example simple. ↩