yegor256
yegor256

Reputation: 105043

How to get classpath in Groovy?

How can I get current value of CLASSPATH in Groovy?

Upvotes: 10

Views: 23746

Answers (6)

M Smith
M Smith

Reputation: 2028

Shameless stolen from http://blog.blindgaenger.net/print_groovys_classpath_for_debugging.html This code will go up the classloader tree and printout each classloader and the associated classpath.

def printClassPath(classLoader) {
  println "$classLoader"
  classLoader.getURLs().each {url->
     println "- ${url.toString()}"
  }
  if (classLoader.parent) {
     printClassPath(classLoader.parent)
  }
}
printClassPath this.class.classLoader

Upvotes: 18

Sergey Orshanskiy
Sergey Orshanskiy

Reputation: 7054

java.class.path doesn't work properly, at least in Groovy 2.1.6 (Mac OS X 10.6.8).

HelloWorld.groovy:

public class HelloWorld {

    public static void main(def args) {
        System.out.println( "Hello, world!\n");
        System.out.println(System.getenv("CLASSPATH")+"\n");
        System.out.println(System.getProperty("java.class.path"));
    }
}

Then

export CLASSPATH=/etc
groovy -classpath /usr HelloWorld.groovy

Result:

Hello, World!

/etc

/Applications/groovy-2.1.6/lib/groovy-2.1.6.jar

Now, this is HelloWorld.java: (I had to change it a bit as Groovy and Java are not 100% compatible):

public class HelloWorld {
    public static void main(String args[]) {
         System.out.println( "Hello, world!\n");
         System.out.println(System.getenv("CLASSPATH")+"\n");
        System.out.println(System.getProperty("java.class.path"));
    }
}

Now:

javac HelloWorld.java
export CLASSPATH=/etc
java -classpath /usr HelloWorld

Result:

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
etc. ...................

Then:

java -classpath /usr:. HelloWorld

Result:

Hello, world!

/etc

/usr:.

I'll update if I find out how to make it work in Groovy...

Upvotes: 1

Edvin Syse
Edvin Syse

Reputation: 7297

You should be able to get the classpath from the SystemClassLoader, providing it is an URLClassLoader:

URL[] classPathUrls = ClassLoader.getSystemClassLoader().getURLs();

Upvotes: 3

anish
anish

Reputation: 7412

Get the CLASSPATH and files if you want in the those CLASSPATH if needed you can view it

System.getProperty("java.class.path", ".").tokenize(File.pathSeparator).each {
                               println it                             
                }

Upvotes: 0

Bozho
Bozho

Reputation: 596996

def classpath = System.properties["java.class.path"]

Upvotes: -1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

This doesn't work?

System.getProperty('java.class.path')

Upvotes: 1

Related Questions