Is there a way to reference the Java class for a Kotlin top-level function?

后端 未结 5 1063

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

5条回答
  •  无人及你
    2020-11-29 10:03

    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 : Any() {}.javaClass.enclosingClass
    

    Note: to work, this declaration should be placed on top level or inside a top-level function.

    Then you can use the topLevelClass as a Class:

    fun main(args: Array) {
        println(topLevelClass) // class MyFileNameKt
    }
    

提交回复
热议问题