Reflection: add KClass.isInstance, KClass.cast, KClass.safeCast

#KT-11284 Fixed
This commit is contained in:
Alexander Udalov
2016-07-12 18:48:37 +03:00
parent 3702f4a7a7
commit ada81923dc
7 changed files with 136 additions and 3 deletions
@@ -236,3 +236,29 @@ fun KClass<*>.isSubclassOf(base: KClass<*>): Boolean =
*/
fun KClass<*>.isSuperclassOf(derived: KClass<*>): Boolean =
derived.isSubclassOf(this)
/**
* Casts the given [value] to the class represented by this [KClass] object.
* Throws an exception if the value is `null` or if it is not an instance of this class.
*
* @see [KClass.isInstance]
* @see [KClass.safeCast]
*/
@Suppress("UNCHECKED_CAST")
fun <T : Any> KClass<T>.cast(value: Any?): T {
if (!isInstance(value)) throw TypeCastException("Value cannot be cast to $qualifiedName")
return value as T
}
/**
* Casts the given [value] to the class represented by this [KClass] object.
* Returns `null` if the value is `null` or if it is not an instance of this class.
*
* @see [KClass.isInstance]
* @see [KClass.cast]
*/
@Suppress("UNCHECKED_CAST")
fun <T : Any> KClass<T>.safeCast(value: Any?): T? {
return if (isInstance(value)) value as T else null
}
@@ -20,6 +20,8 @@ import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.structure.reflect.functionClassArity
import org.jetbrains.kotlin.load.java.structure.reflect.wrapperByPrimitive
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.reflect.ReflectKotlinClass
import org.jetbrains.kotlin.name.ClassId
@@ -27,6 +29,7 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.serialization.deserialization.findClassAcrossModuleDependencies
import kotlin.jvm.internal.TypeIntrinsics
import kotlin.reflect.*
internal class KClassImpl<T : Any>(override val jClass: Class<T>) :
@@ -136,6 +139,14 @@ internal class KClassImpl<T : Any>(override val jClass: Class<T>) :
override val objectInstance: T?
get() = objectInstance_()
override fun isInstance(value: Any?): Boolean {
// TODO: use Kotlin semantics for mutable/read-only collections once KT-11754 is supported (see TypeIntrinsics)
jClass.functionClassArity?.let { arity ->
return TypeIntrinsics.isFunctionOfArity(value, arity)
}
return (jClass.wrapperByPrimitive ?: jClass).isInstance(value)
}
override val typeParameters: List<KTypeParameter>
get() = descriptor.declaredTypeParameters.map(::KTypeParameterImpl)