Is there a way to reference the Java class for a Kotlin top-level function?
Solution 1:
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
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<out Any>
:
fun main(args: Array<String>) {
println(topLevelClass) // class MyFileNameKt
}
Solution 2:
With Java 7 you can get a reference to the current Java class from a top level function using
MethodHandles.lookup().lookupClass()
Solution 3:
No, there is no syntax to reference that class. You can access it using Class.forName(). For example, if the file is called "Hello.kt" and is located in the package "demo", you can obtain the class by calling Class.forName("demo.HelloKt")
.