Scott Frederick's humble blog

on sofware development and technology

Getting the Classpath With Groovy

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
def getClassPath() {
   def loaderUrls = this.class.classLoader.rootLoader.URLs
   def files = loaderUrls.collect { new URI(it.toString()).path - '/'}
   return files.join(File.pathSeparator)
}

println getClassPath()

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
class ClassPathTestClass {
   static void main(args) {
      println new ClassPathTestClass().getClassPath()
   }

   def getClassPath() {
      def loaderUrls = this.class.classLoader.URLs
      def files = loaderUrls.collect { new URI(it.toString()).path - '/' }
      return files.join(File.pathSeparator)
   }
}

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 this.class.classLoader.URLs.

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.