SyntaxHighlighter

Friday, May 28, 2010

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:

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):

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.

No comments:

Post a Comment