简体   繁体   中英

How to get classpath in Groovy?

如何在Groovy中获取CLASSPATH当前值?

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

您应该能够从SystemClassLoader获取类路径,前提是它是一个URLClassLoader:

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

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...

这不起作用?

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

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                             
                }
def classpath = System.properties["java.class.path"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM