Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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(...))
like image 632
Duncan McGregor Avatar asked Jan 22 '16 16:01

Duncan McGregor


People also ask

How do you call a Java class in Kotlin?

Kotlin code access Java array We can simply call Java class method which takes array as an argument from Kotlin file. For example, create method sumValue() which takes array element as parameter in Java class MyJava. java calculating addition and returns result. This method is called from Kotlin file MyKotlin.

How do I reference a class in Kotlin?

To obtain the reference to a statically known Kotlin class, you can use the class literal syntax: val c = MyClass::class //The reference is a value of type KClass.

Can we call top-level function in Java?

you can refer to top-level functions from Java by the file name ( File1. foo() ), renaming a file requires the clients to be recompiled, unless you have customized the class name with the annotation.

Can Java and Kotlin work together?

If your question is can you use kotlin files in java files and vice versa then the answer is yes.


4 Answers

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
}
like image 152
hotkey Avatar answered Oct 24 '22 10:10

hotkey


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

MethodHandles.lookup().lookupClass()
like image 26
hunterwb Avatar answered Oct 24 '22 11:10

hunterwb


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

like image 40
yole Avatar answered Oct 24 '22 11:10

yole


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(...)
like image 29
Duncan McGregor Avatar answered Oct 24 '22 12:10

Duncan McGregor