Support KClass.objectInstance for objects and companion objects
This commit is contained in:
@@ -19,6 +19,7 @@ package kotlin.reflect.jvm.internal
|
||||
import org.jetbrains.kotlin.descriptors.ClassKind
|
||||
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.annotations.Annotated
|
||||
import org.jetbrains.kotlin.load.java.JvmAbi
|
||||
import org.jetbrains.kotlin.name.ClassId
|
||||
import org.jetbrains.kotlin.resolve.scopes.ChainedScope
|
||||
import org.jetbrains.kotlin.resolve.scopes.JetScope
|
||||
@@ -27,7 +28,7 @@ import kotlin.reflect.KClass
|
||||
import kotlin.reflect.KFunction
|
||||
import kotlin.reflect.KotlinReflectionInternalError
|
||||
|
||||
class KClassImpl<T>(override val jClass: Class<T>) : KCallableContainerImpl(), KClass<T>, KAnnotatedElementImpl {
|
||||
class KClassImpl<T : Any>(override val jClass: Class<T>) : KCallableContainerImpl(), KClass<T>, KAnnotatedElementImpl {
|
||||
val descriptor by ReflectProperties.lazySoft {
|
||||
val classId = classId
|
||||
|
||||
@@ -92,6 +93,20 @@ class KClassImpl<T>(override val jClass: Class<T>) : KCallableContainerImpl(), K
|
||||
KFunctionImpl(this, it) as KFunction<T>
|
||||
}
|
||||
|
||||
@suppress("UNCHECKED_CAST")
|
||||
override val objectInstance: T? by ReflectProperties.lazy {
|
||||
val descriptor = descriptor
|
||||
if (descriptor.kind != ClassKind.OBJECT) return@lazy null
|
||||
|
||||
val field = if (descriptor.isCompanionObject) {
|
||||
jClass.enclosingClass.getDeclaredField(descriptor.name.asString())
|
||||
}
|
||||
else {
|
||||
jClass.getDeclaredField(JvmAbi.INSTANCE_FIELD)
|
||||
}
|
||||
field.get(null) as T
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean =
|
||||
other is KClassImpl<*> && jClass == other.jClass
|
||||
|
||||
|
||||
Reference in New Issue
Block a user