https://kotlinlang.org logo
#getting-started
Title
# getting-started
h

hichem fazai

01/28/2022, 1:52 PM
Hi everyone, Is it possible to get the file name of a class? For example I have Foo.kt containing this class:
Copy code
class Bar {
  init {
    // Here I want to get the name of the file (Foo)
  }
}
j

Joffrey

01/28/2022, 1:54 PM
The source file doesn't necessarily exist at runtime. If your class is compiled into a
.class
file which is then packaged into a jar, what file name do you expect to get when you run this program?
Maybe you can use Java reflection like:
Copy code
Bar::class.java.protectionDomain.codeSource.location.path
But it might not be 100% guaranteed to be accessible
h

hichem fazai

01/28/2022, 1:59 PM
I tried this but it gives the path to the main function.
If the source file doesnt exist in the runtime, so how the stacktrace shows it?
If you execute this:
Copy code
fun main() {
  Bar()
}

class Bar {
  init {
    throw Exception()
  }
}
output:
Exception in thread "main" java.lang.Exception
at Bar.<init>(Foo.kt:7)
at FooKt.main(Foo.kt:2)
at FooKt.main(Foo.kt)
What do you think about the code below?
Copy code
class Bar {
  init {
    val name = Exception().stackTrace.first().fileName.removeSuffix(".kt")
  }
}
😟 1
It works for me but looks very hacky
j

Joffrey

01/28/2022, 2:13 PM
Seems indeed quite hacky to me. Maybe there is something in Kotlin's Metadata on the class that you could use. But I don't know much about this
Why are you interested in the filename at runtime btw?
h

hichem fazai

01/28/2022, 2:26 PM
Here is my use case I have a containing some classes that represents visual forms. That forms contains too many informations like title, labels of the fields, ... etc. Now I want to provide a way to localize these forms in one xml file. So the method will be like this:
Copy code
fun localize(form: Form) {
  val name = form.fileName()
  // if language is french, look for localization in the file name-fr_FR.xml
  // if language is english, look for localization in the file name-en_GB.xml
}
j

Joffrey

01/28/2022, 2:33 PM
So basically you want to associate
Form
instances with XML files based on the name of the file containing the form? Why not base this on a convention on class name? Or just specifying the file prefix explicitly in each form (which is more refactoring-proof)?
h

hichem fazai

01/28/2022, 2:49 PM
Yes exactly, I was trying to reduce code and make the program deduct that information. Actually it's based on classname but to make the components in the form reusable it's possible to create a class for a field and insert it in a form. This way I will have to write an xml file foreach field. That's why I wanted to regroup localization of many classes in same xml file. Also you're right about specifying the file prefix explicitly to avoid refactoring problem.
Thanks alot for the ideas and help! I invite you to take a look at this framework and the DSL I'm building: https://github.com/kopiLeft/Galite#form
👍 1