如何在kotlin中获取当前的类文件名

poz*_*ndw 3 java kotlin

在Java中,我可以使用以下代码:

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

但是在Kotlin中,主要功能是在课外定义的.我怎样才能得到它的当前文件名?

Eug*_*nja 5

作为解决方法,将main方法放入伴随对象.
此代码将显示与Java代码相同的路径:

class ExKt {
  companion object {
    @JvmStatic fun main(args: Array<String>) {
        val path = ExKt::class.java.protectionDomain.codeSource.location.path
        println("Kotlin: " + path)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


poz*_*ndw -6

解决办法是:

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

fun main(args: Array<String>) {
    Ex().m()
}
Run Code Online (Sandbox Code Playgroud)