给定类的实例,我正在尝试使用已知接口访问未知类的伴随对象。
下面的代码:
class AccessTest() {
companion object {
val prop = 5
}
fun getComp() {
print(this)
print(this::class)
print(this::class.companionObject) // Unresolved reference.
print(this::class.companionObjectInstance) // Unresolved reference.
}
}
inline fun <reified T> getCompanion() {
print(T::class.companionObject) // Unresolved reference.
print(T::class.companionObjectInstance) // Unresolved reference.
}
fun main() {
AccessTest().getComp()
getCompanion<AccessTest>()
}
输出:
$ kotlinc -d main.jar main.kt && kotlin -classpath main.jar MainKt
main.kt:8:27: error: unresolved reference: companionObject
print(this::class.companionObject) // Unresolved reference.
^
main.kt:9:27: error: unresolved reference: companionObjectInstance
print(this::class.companionObjectInstance) // Unresolved reference.
^
main.kt:14:20: error: unresolved reference: companionObject
print(T::class.companionObject) // Unresolved reference.
^
main.kt:15:20: error: unresolved reference: companionObjectInstance
print(T::class.companionObjectInstance) // Unresolved reference.
^
我认为这不是以下任何一个问题的重复,因为我特意询问发生了什么变化或我误解了什么,因此以下两个问题中的解决方案对我不起作用: