有没有办法为Kotlin顶级功能引用Java类? [英] Is there a way to reference the Java class for a Kotlin top-level function?

查看:105
本文介绍了有没有办法为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(...))

推荐答案

我发现的另一种方法是在顶级函数内声明本地类或匿名对象并获取其enclosingClass:

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

注意:要起作用,此声明应放在顶层或顶层函数内.

然后您可以将topLevelClass用作Class<out Any>:

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

这篇关于有没有办法为Kotlin顶级功能引用Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆