8

In Java I can use the following code:

public class Ex {
    public static void main(String [ ] args) {
        String path = Ex.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String decodedPath = URLDecoder.decode(path, "UTF-8");
    }
}

but in Kotlin, the main function is defined outside out of a class. How can I get it's current file name?

Mibac
  • 8,990
  • 5
  • 33
  • 57
pozklundw
  • 505
  • 1
  • 9
  • 16

2 Answers2

6

As a workaround, put main method into companion object.
This code will show a same path as your Java code:

class ExKt {
  companion object {
    @JvmStatic fun main(args: Array<String>) {
        val path = ExKt::class.java.protectionDomain.codeSource.location.path
        println("Kotlin: " + path)
    }
  }
}
Eugene Krivenja
  • 647
  • 8
  • 18
  • for some reason, protectionDomain returns null for Android Activity class :( – Liker777 Oct 14 '21 at 04:29
  • @Liker777, this code is not compatible with Android runtime. See https://stackoverflow.com/questions/27790348/getclass-getprotectiondomain-getcodesource-getlocation-getpath-throw-a – Eugene Krivenja Oct 14 '21 at 15:18
  • thank you. As an alternative, I got the file name with extension via stacktrace, the remaining thing is how to find a path to that file. Walkaround is recursive search in the package for the file name, but I believe there should be simpler way to return a full path... – Liker777 Oct 15 '21 at 03:28
-6

The solution is:

class Ex() {
    fun m() {
        var p2 = Ex::class.java.simpleName
        println("p2:${p2}")
    }
}

fun main(args: Array<String>) {
    Ex().m()
}
pozklundw
  • 505
  • 1
  • 9
  • 16
  • 1
    It's nice that this code solves your problem, but it isn't an answer to your original question. This code returns the name of the Java class, not the name of the file from which it was compiled. – yole Jan 07 '16 at 13:11
  • Agree with @yole, additionally you could call `Ex::class.java.simpleName` directly from the `main`, creating a `Ex` instance doesn't make sense there. – Eugene Krivenja Jan 07 '16 at 13:57