Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current class filename in kotlin

Tags:

java

kotlin

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?

like image 546
pozklundw Avatar asked Jan 07 '16 10:01

pozklundw


People also ask

How do I find my current class name in Kotlin?

Since Kotlin 1.1, you can use the ::class syntax to get the KClass . There are several different implementations to get the class name as per your requirements. Additionally, you can use KClass. js to access the JsClass instance corresponding to the class.

How do I find my current path in Kotlin?

In the above program, we used Path 's get() method to get the current path of our program. This returns a relative path to the working directory. We then change the relative path to absolute path using toAbsolutePath() . Since, it returns a Path object, we need to change it to a string using toString() method.

How do I find the filename of a file?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);


1 Answers

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)
    }
  }
}
like image 154
Eugene Krivenja Avatar answered Nov 15 '22 10:11

Eugene Krivenja