How can I get current value of CLASSPATH
in Groovy?
6 Answers
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
You should be able to get the classpath from the SystemClassLoader, providing it is an URLClassLoader:
URL[] classPathUrls = ClassLoader.getSystemClassLoader().getURLs();
-
1Same thing: both the
CLASSPATH
environment variable and the-classpath
in the command line have no effect on this list. At least in my case it is identical to what I see in the propertyjava.class.path
. Oct 11, 2013 at 20:21 -
1However, see groovy.codehaus.org/… about dynamically adding a path to classpath. this.class.classLoader.rootLoader.addURL( new URL("file:///d:/drivers/ojdbc14.jar") ) Oct 11, 2013 at 20:39
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...
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
}
This doesn't work?
System.getProperty('java.class.path')
-
3
-
3Groovy seems to do funky stuff, and the java.class.path does not contain the classpath passed with groovy's -cp command line option. Sep 20, 2011 at 12:41
-
2It shows only groovy jar - why stackoverflow.com/a/27131375/1042297 is not accepted answer ?– kodstarkAug 12, 2016 at 17:13
def classpath = System.properties["java.class.path"]
-
Unfortunately it's empty when I'm using Groovy inside gmaven plugin. Is it possible to get classpath from class loader somehow?– yegor256Mar 6, 2011 at 18:55