In a recent Groovy project, I needed to get the classpath that was used to start the program so I could pass it as a command-line parameter to another program being launched.
You can easily get the the list of classpath URLs used by the program’s classloader. Most of the hints I found showed how to do this from a Groovy script, but it appears to work a little differently in a program.
Here is the code I came up with to get the classpath in a script:
1 2 3 4 5 6 7
And here is the same code in a program (i.e. a class with a main):
1 2 3 4 5 6 7 8 9 10 11
The difference is in how the list of URLs is initially retrieved. From a script you can get the list with
this.class.classLoader.rootLoader.URLs. In a program you use
The second line in each of the
getClassPath methods took more tweaking than expected. The
new URI(it.toString()).path - '/' syntax removes any encoding from the URL paths and strips everything but the path out of the URL. This has only been tested on Windows, I’m not sure if this will work exactly the same on other platforms.