有没有办法为 Kotlin 顶级函数引用 Java 类? [英] Is there a way to reference the Java class for a Kotlin top-level function?
本文介绍了有没有办法为 Kotlin 顶级函数引用 Java 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 Class.getResourceAsStream()
在顶级函数中加载资源.
I want to load a resource in a top level function using Class.getResourceAsStream()
.
有什么方法可以得到对顶级函数将被编译成的类的引用,以便我可以编写,例如
Is there any way to get a reference to the class that the top level function will be compiled into so that I can write, for example
val myThing = readFromStream(MYCLASS.getResourceAsStream(...))
推荐答案
我发现的另一种方法是在顶级函数中声明一个本地类或匿名对象并获取它的 enclosureClass
:
Another way I found is to declare a local class or an anonymous object inside a top level function and to get its enclosingClass
:
val topLevelClass = object{}.javaClass.enclosingClass
注意:为了工作,这个声明应该放在顶层或顶层函数内.
然后你可以使用topLevelClass
作为Class
:
fun main(args: Array<String>) {
println(topLevelClass) // class MyFileNameKt
}
这篇关于有没有办法为 Kotlin 顶级函数引用 Java 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文