In Kotlin/JVM when using Progaurd to minimize Desktop applications, when trying to get the current running JAR file path, usually we would use the following code snippet:
var codeSource =
object {}
.javaClass.enclosingClass
?.protectionDomain
?.codeSource
codeSource
will return null if Proguard obfuscation is enabled, otherwise when Proguard obfuscation is disabled (Proguard is still used) it will be not null when we’re running the application as JAR as expected.
When Progaurd obfuscation is enabled, the only way to get the current running JAR file path is by:
val stack = Thread.currentThread().stackTrace
val main = stack[stack.size - 1]
val mainClassName = main.className
val codeSource =
Class
.forName(mainClassName)
.javaClass.protectionDomain.codeSource
By using Dynamic class loading, there is probably a technical reason why this behavior is like this, is there any recommended way to get the current running JAR file when using Progaurd? or why codeSource
is null when accessing it like this object {} .javaClass.enclosingClass ?.protectionDomain ?.codeSource
and Proguard obfuscation is enabled
Notice that using val codeSource = object {}.javaClass.protectionDomain?.codeSource
always works as expected, even if we’re using Proguard obfuscation. I still would like to know why the issue happens when using enclosingClass
and Proguard obfuscation enabled.
Thank you.