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

How to get current class filename in 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");
    }
}

但在 Kotlin 中,main 函数是在 class 之外定义的。我怎样才能得到它的当前文件名?

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

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

解决方法是:

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

fun main(args: Array<String>) {
    Ex().m()
}