
KType. Types should not be confused with classes. Variables and parameters have types, not classes. Types can be nullable and can have type arguments1I explained the differences between classes and types in the The beauty of Kotlin’s type system chapter of Kotlin Essentials..
Examples of types and classes. This image was first published in my book Kotlin Essentials.

Relations between classes, types and objects. This image was first published in my book Kotlin Essentials.
typeOf function. Note that this function holds information about nullability and type arguments.import kotlin.reflect.KType import kotlin.reflect.typeOf fun main() { val t1: KType = typeOf<Int?>() println(t1) // kotlin.Int? val t2: KType = typeOf<List<Int?>>() println(t2) // kotlin.collections.List<kotlin.Int?> val t3: KType = typeOf<() -> Map<Int, Char?>>() println(t3) // () -> kotlin.collections.Map<kotlin.Int, kotlin.Char?> }
KType is a simple class with only three properties: isMarkedNullable, arguments, and classifier.// Simplified KType definition interface KType : KAnnotatedElement { val isMarkedNullable: Boolean val arguments: List<KTypeProjection> val classifier: KClassifier? }
isMarkedNullable property is simplest; it returns true if this type is marked as nullable in the source code.import kotlin.reflect.typeOf fun main() { println(typeOf<Int>().isMarkedNullable) // false println(typeOf<Int?>().isMarkedNullable) // true }
arguments provide type arguments of this type, so the List<Int> type will have a single argument of type Int, and Map<Long, Char> will have two type arguments Long and Char. The type of these type arguments is KTypeProjection, which is a data class that includes type and a potential variance modifier, therefore Box<out String> has one type argument: out String.// Simplified KTypeProjection definition data class KTypeProjection( val variance: KVariance?, val type: KType? )
import kotlin.reflect.typeOf class Box<T> fun main() { val t1 = typeOf<List<Int>>() println(t1.arguments) // [kotlin.Int] val t2 = typeOf<Map<Long, Char>>() println(t2.arguments) // [kotlin.Long, kotlin.Char] val t3 = typeOf<Box<out String>>() println(t3.arguments) // [out kotlin.String] }
classifier property, which is a way for a type to reference the associated class. Its result type is KClassifier?, which is a supertype of KClass and KTypeParameter. KClass represents a class or an interface. KTypeParameter represents a generic type parameter. The type classifier can be KTypeParameter when we reference generic class members. Also, classifier returns null when the type is not denotable in Kotlin, e.g., an intersection type.import kotlin.reflect.* class Box<T>(val value: T) { fun get(): T = value } fun main() { val t1 = typeOf<List<Int>>() println(t1.classifier) // class kotlin.collections.List println(t1 is KType) // true println(t1 is KClass<*>) // false val t2 = typeOf<Map<Long, Char>>() println(t2.classifier) // class kotlin.collections.Map println(t2.arguments[0].type?.classifier) // class kotlin.Long val t3 = Box<Int>::get.returnType.classifier println(t3) // T println(t3 is KTypeParameter) // true }
// KTypeParameter definition interface KTypeParameter : KClassifier { val name: String val upperBounds: List<KType> val variance: KVariance val isReified: Boolean }
ValueGenerator class with a randomValue method that generates a random value of a specific type. We will specify two variants of this function: one expecting a type as a reified type argument, and another that expects a type reference as a regular argument.class ValueGenerator( private val random: Random = Random, ) { inline fun <reified T> randomValue(): T = randomValue(typeOf<T>()) as T fun randomValue(type: KType): Any? = TODO() }
randomValue function, a philosophical problem arises: if a type is nullable, what is the probability that our random value is null? To solve this problem, I added a configuration that specifies the probability of a null value.import kotlin.random.Random import kotlin.reflect.KType import kotlin.reflect.typeOf class RandomValueConfig( val nullProbability: Double = 0.1, ) class ValueGenerator( private val random: Random = Random, val config: RandomValueConfig = RandomValueConfig(), ) { inline fun <reified T> randomValue(): T = randomValue(typeOf<T>()) as T fun randomValue(type: KType): Any? = when { type.isMarkedNullable -> randomNullable(type) // ... else -> error("Type $type not supported") } private fun randomNullable(type: KType) = if (randomBoolean(config.nullProbability)) null else randomValue(type.withNullability(false)) private fun randomBoolean(probability: Double) = random.nextDouble() < probability }
Boolean is simplest because it can be generated using nextBoolean from Random. The same can be said about Int, but 0 is a special value, so I decided to specify its probability in the configuration as well.//sampleStart import kotlin.math.ln import kotlin.random.Random import kotlin.reflect.KType // import kotlin.reflect.full.isSubtypeOf // replaced by reflect-lite import kotlin.reflect.typeOf class RandomValueConfig( val nullProbability: Double = 0.1, val zeroProbability: Double = 0.1, ) class ValueGenerator( private val random: Random = Random, val config: RandomValueConfig = RandomValueConfig(), ) { inline fun <reified T> randomValue(): T = randomValue(typeOf<T>()) as T fun randomValue(type: KType): Any? = when { type.isMarkedNullable && randomBoolean(config.nullProbability) -> null type == typeOf<Boolean>() -> randomBoolean() type == typeOf<Int>() -> randomInt() // ... else -> error("Type $type not supported") } private fun randomInt() = if (randomBoolean(config.zeroProbability)) 0 else random.nextInt() private fun randomBoolean() = random.nextBoolean() private fun randomBoolean(probability: Double) = random.nextDouble() < probability } //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 =====
List<List<List<String>>> could literally consume all our memory, not to mention the fact that the readability of such objects would be poor. But we should also make it possible for our function to generate a big collection or a string as this might be an edge case we need in some unit tests. I believe that the sizes of the collections and strings we use in real projects are described with exponential distribution: most of them are rather short, but some are huge. The exponential distribution is parametrized with a lambda value. I made this parameter configurable. By default, I decided to specify the exponential distribution parameter for strings as 0.1, which makes our function generate an empty string with around 10% probability, and a string longer than 5 characters with around55% probability. For lists, I specify the default parameter as
0.3, which means that lists will be empty with around 25% probability, and they have only 16% probability of having a size greater than 5.//sampleStart import kotlin.math.ln import kotlin.random.Random import kotlin.reflect.KType // import kotlin.reflect.full.isSubtypeOf // replaced by reflect-lite // import kotlin.reflect.full.withNullability // replaced by reflect-lite import kotlin.reflect.typeOf class RandomValueConfig( val nullProbability: Double = 0.1, val zeroProbability: Double = 0.1, val stringSizeParam: Double = 0.1, val listSizeParam: Double = 0.3, ) class ValueGenerator( private val random: Random = Random, val config: RandomValueConfig = RandomValueConfig(), ) { inline fun <reified T> randomValue(): T = randomValue(typeOf<T>()) as T fun randomValue(type: KType): Any? = when { type.isMarkedNullable -> randomNullable(type) type == typeOf<Boolean>() -> randomBoolean() type == typeOf<Int>() -> randomInt() type == typeOf<String>() -> randomString() type.isSubtypeOf(typeOf<List<*>>()) -> randomList(type) // ... else -> error("Type $type not supported") } private fun randomNullable(type: KType) = if (randomBoolean(config.nullProbability)) null else randomValue(type.withNullability(false)) private fun randomString(): String = (1..random.exponential(config.stringSizeParam)) .map { CHARACTERS.random(random) } .joinToString(separator = "") private fun randomList(type: KType) = List(random.exponential(config.listSizeParam)) { randomValue(type.arguments[0].type!!) } private fun randomInt() = if (randomBoolean(config.zeroProbability)) 0 else random.nextInt() private fun randomBoolean() = random.nextBoolean() private fun randomBoolean(probability: Double) = random.nextDouble() < probability companion object { private val CHARACTERS = ('A'..'Z') + ('a'..'z') + ('0'..'9') + " " } } private fun Random.exponential(f: Double): Int { return (ln(1 - nextDouble()) / -f).toInt() } //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 =====
fun main() { val r = Random(1) val g = ValueGenerator(random = r) println(g.randomValue<Int>()) // -527218591 println(g.randomValue<Int?>()) // -2022884062 println(g.randomValue<Int?>()) // null println(g.randomValue<List<Int>>()) // [-1171478239] println(g.randomValue<List<List<Boolean>>>()) // [[true, true, false], [], [], [false, false], [], // [true, true, true, true, true, true, true, false]] println(g.randomValue<List<Int?>?>()) // [-416634648, null, 382227801] println(g.randomValue<String>()) // WjMNxTwDPrQ println(g.randomValue<List<String?>>()) // [VAg, , null, AIKeGp9Q7, 1dqARHjUjee3i6XZzhQ02l, DlG, , ] }
Added 1 as a seed value toRandomto produce predictable pseudo-random values for demonstration purposes.
classifier property and constructors. Nevertheless, let's stop where we are.java property to transform KClass to Java Class, or we can use javaMethod to transform KFunction to Method. Similarly, we can transform Java Reflection classes to Kotlin Reflection classes using extension properties which start with the kotlin prefix. For example, we can use the kotlin property to transform Class to KClass, and the kotlinFunction property to transform Method to KFunction.//sampleStart import java.lang.reflect.* import kotlin.reflect.* // import kotlin.reflect.jvm.* // replaced by reflect-lite class A { val a = 123 fun b() {} } fun main() { val c1: Class<A> = A::class.java val c2: Class<A> = A().javaClass val f1: Field? = A::a.javaField val f2: Method? = A::a.javaGetter val f3: Method? = A::b.javaMethod val kotlinClass: KClass<A> = c1.kotlin val kotlinProperty: KProperty<*>? = f1?.kotlinProperty val kotlinFunction: KFunction<*>? = f3?.kotlinFunction } //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 =====
isAccessible property in the Kotlin and Java Reflection APIs. The same property can be used to change elements’ accessibility. When we do that, we can call private functions or operate on private properties. Of course, you should avoid doing this if not absolutely necessary.//sampleStart import kotlin.reflect.* // import kotlin.reflect.full.* // replaced by reflect-lite // import kotlin.reflect.jvm.isAccessible // replaced by reflect-lite class A { private var value = 0 private fun printValue() { println(value) } override fun toString(): String = "A(value=$value)" } fun main() { val a = A() val c = A::class // We change value to 999 val prop = c.declaredMemberProperties .find { it.name == "value" } as? KMutableProperty1<A, Int> prop?.isAccessible = true prop?.set(a, 999) println(a) // A(value=999) println(prop?.get(a)) // 999 // We call printValue function val func: KFunction<*>? = c.declaredMemberFunctions .find { it.name == "printValue" } func?.isAccessible = true func?.call(a) // 999 } //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 =====
- 1.I explained the differences between classes and types in the The beauty of Kotlin’s type system chapter of Kotlin Essentials. ↩