如何反射声明在顶层文件中的变量和方法呢?


#1

想反射声明的顶层变量和方法,如何拿到Kclass呢


#2

顶层的函数和变量没有类,所以不存在 KClass。


#3

const val MM = “HHHHHH”

var enclos = object : Any(){}.javaClass.enclosingClass?.kotlin

fun main(){

println(enclos)

enclos?.declaredMemberProperties?.forEach {
print(it.name)
}
}

应该算是有一个TTKt文件名的类,但是好像真的不行。
输出:
class com.foundersc.portal.TTKt

Exception in thread “main” java.lang.UnsupportedOperationException: Packages and file facades are not yet supported in Kotlin reflection. Meanwhile please use Java reflection to inspect this class: class com.foundersc.portal.TTKt
at kotlin.reflect.jvm.internal.KClassImpl.reportUnresolvedClass(KClassImpl.kt:301)
at kotlin.reflect.jvm.internal.KClassImpl.access$reportUnresolvedClass(KClassImpl.kt:43)
at kotlin.reflect.jvm.internal.KClassImpl$Data$descriptor$2.invoke(KClassImpl.kt:53)
at kotlin.reflect.jvm.internal.KClassImpl$Data$descriptor$2.invoke(KClassImpl.kt:44)
at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(ReflectProperties.java:92)
at kotlin.reflect.jvm.internal.ReflectProperties$Val.getValue(ReflectProperties.java:31)
at kotlin.reflect.jvm.internal.KClassImpl$Data.getDescriptor(KClassImpl.kt)
at kotlin.reflect.jvm.internal.KClassImpl.getDescriptor(KClassImpl.kt:179)
at kotlin.reflect.jvm.internal.KClassImpl.getMemberScope$kotlin_reflection(KClassImpl.kt:188)
at kotlin.reflect.jvm.internal.KClassImpl$Data$declaredNonStaticMembers$2.invoke(KClassImpl.kt:159)
at kotlin.reflect.jvm.internal.KClassImpl$Data$declaredNonStaticMembers$2.invoke(KClassImpl.kt:44)
at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(ReflectProperties.java:92)
at kotlin.reflect.jvm.internal.ReflectProperties$Val.getValue(ReflectProperties.java:31)
at kotlin.reflect.jvm.internal.KClassImpl$Data.getDeclaredNonStaticMembers(KClassImpl.kt)
at kotlin.reflect.full.KClasses.getDeclaredMemberProperties(KClasses.kt:163)
at com.foundersc.portal.TTKt.main(TT.kt:19)
at com.foundersc.portal.TTKt.main(TT.kt)


#4

使用 Java 反射是可以访问的,但 Kotlin 反射应该是不行的


京ICP备16022265号-2 Kotlin China 2017 - 2018