Support KClass.companionObject and companionObjectInstance

#KT-7636 Fixed
This commit is contained in:
Alexander Udalov
2015-08-25 09:34:45 +03:00
parent 94d45f35d4
commit 9a8cf23ed4
3 changed files with 44 additions and 0 deletions
@@ -0,0 +1,20 @@
import kotlin.reflect.*
import kotlin.test.*
class A {
companion object C
}
fun box(): String {
val obj = A::class.companionObject
assertNotNull(obj)
assertEquals("C", obj!!.simpleName)
assertEquals(A.C, A::class.companionObjectInstance)
assertEquals(A.C, obj.objectInstance)
assertNull(A.C::class.companionObject)
assertNull(A.C::class.companionObjectInstance)
return "OK"
}
@@ -3012,6 +3012,12 @@ public class BlackBoxWithStdlibCodegenTestGenerated extends AbstractBlackBoxCode
doTestWithStdlib(fileName);
}
@TestMetadata("companionObject.kt")
public void testCompanionObject() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/classes/companionObject.kt");
doTestWithStdlib(fileName);
}
@TestMetadata("defaultType.kt")
public void testDefaultType() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/classes/defaultType.kt");
@@ -31,6 +31,24 @@ public val <T : Any> KClass<T>.primaryConstructor: KFunction<T>?
((it as KFunctionImpl).descriptor as ConstructorDescriptor).isPrimary
}
/**
* Returns a [KClass] instance representing the companion object of a given class,
* or `null` if the class doesn't have a companion object.
*/
public val KClass<*>.companionObject: KClass<*>?
get() = nestedClasses.firstOrNull {
(it as KClassImpl<*>).descriptor.isCompanionObject
}
/**
* Returns an instance of the companion object of a given class,
* or `null` if the class doesn't have a companion object.
*/
public val KClass<*>.companionObjectInstance: Any?
get() = companionObject?.objectInstance
/**
* Returns a type corresponding to the given class with type parameters of that class substituted as the corresponding arguments.
* For example, for class `MyMap<K, V>` [defaultType] would return the type `MyMap<K, V>`.