简体   繁体   English

如何在Groovy中获取classpath?

[英]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. 来自http://blog.blindgaenger.net/print_groovys_classpath_for_debugging.html的无耻窃取此代码将上升到类加载器树并打印出每个类加载器和相关的类路径。

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). java.class.path无法正常工作,至少在Groovy 2.1.6(Mac OS X 10.6.8)中是这样。

HelloWorld.groovy : 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): 现在,这是HelloWorld.java :(我不得不改变它,因为Groovy和Java不是100%兼容):

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... 如果我发现如何使它在Groovy中工作,我会更新...

这不起作用?

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

Get the CLASSPATH and files if you want in the those CLASSPATH if needed you can view it 如果需要,可以获取CLASSPATH和文件,如果需要,可以查看它

System.getProperty("java.class.path", ".").tokenize(File.pathSeparator).each {
                               println it                             
                }
def classpath = System.properties["java.class.path"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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