Is there a way to reference the Java class for a K

2019-08-25 01:16发布

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(...))

标签: java kotlin
5条回答
不美不萌又怎样
2楼-- · 2019-08-25 01:43

With Java 7 you can get a reference to the current Java class from a top level function using

MethodHandles.lookup().lookupClass()
查看更多
何必那么认真
3楼-- · 2019-08-25 01:50

In the absence of a way to get a reference directly, I've fallen back on creating an anonymous object in the current package

val myThing = object: Any() {}.javaClass.getResourceAsStream(...)
查看更多
三岁会撩人
4楼-- · 2019-08-25 02:00

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<out Any>:

fun main(args: Array<String>) {
    println(topLevelClass) // class MyFileNameKt
}
查看更多
在下西门庆
5楼-- · 2019-08-25 02:01

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").

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-08-25 02:06

As linters like detekt would flag anonymous classes as EmptyClassBlock you could also use something like

internal object Resources

fun resourceStream(name: String): InputStream {
    return Resources.javaClass.getResourceAsStream(name)
}
查看更多
登录 后发表回答