Get class reference from top level function in kotlin

I wrote a short program that does not require any classes and, in turn, contains only top-level functions.

To find your jar location from java code you write

MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath() 

But since I did not declare any classes in my Kotlin code, I do not know how to get a reference to the class.

My current implementation is

 class Ref val jarPath = Ref::class.java.protectionDomain.codeSource.location.toURI().path 

which is obviously very bad code.

So my question is: how to get a class reference in kotlin without declaring any unnecessary classes. Any tips appreciated :)

+5
source share
1 answer

You can declare a class, but anonymous, using an expression so that it is not visible to the surrounding code:

 val jarPath = object {}.javaClass.protectionDomain.codeSource.location.toURI().path 
+7
source

All Articles