Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class reference from top level function in kotlin [duplicate]

Tags:

class

kotlin

I wrote a short program which does not require any classes and in turn consits of top level functions only.

To find your jar's location from java code you write

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

But as I did not declare any classes in my kotlin code I don't know how to get a class reference.

My current implementation is this

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

which is obviously very bad code.

So my question is, how do I obtain a class reference in kotlin without declaring any unneccesary classes. Any hints appreciated :)

like image 960
succcubbus Avatar asked Jul 06 '16 18:07

succcubbus


1 Answers

You can declare a class, but an anonymous one using the object expression, so that it won't be visible to the surrounding code:

val jarPath = object {}.javaClass.protectionDomain.codeSource.location.toURI().path
like image 144
Alexander Udalov Avatar answered Nov 07 '22 21:11

Alexander Udalov