简体   繁体   English

SystemClassLoader的Groovy脚本类路径问题

[英]Groovy script classpath issue with SystemClassLoader

I'm writing a Groovy script which uses third party java code that I can't change. 我正在编写一个Groovy脚本,该脚本使用无法更改的第三方Java代码。 This code uses (badly, I think) ClassLoader.getSystemClassLoader().getResourceAsStream("/hard/file/path/in/jar/file") and expect to read a file. 这段代码使用(非常糟糕,我认为) ClassLoader.getSystemClassLoader().getResourceAsStream("/hard/file/path/in/jar/file")并希望读取文件。

Everything goes well from Java when using java -cp "/path/to/jar/file" ... 使用java -cp "/path/to/jar/file" ...时,Java一切正常java -cp "/path/to/jar/file" ...

However, the third-party code is now to be integrated with a bunch of Groovy code we've already written, so we wanted to run it from groovy. 但是,现在将第三方代码与我们已经编写的一堆Groovy代码集成在一起,因此我们想从groovy运行它。

So we wrote a Groovy script, let it call test.groovy , and ran it as groovy -cp "/path/to/jar/file" test.groovy . 因此,我们编写了一个Groovy脚本,将其称为test.groovy ,并将其作为groovy -cp "/path/to/jar/file" test.groovy

The problem is that code can't access the file resource, as it seems Groovy doesn't load its jars in the System ClassLoader directly. 问题是代码无法访问文件资源,因为Groovy似乎没有直接在系统类加载器中加载其jar。

For proof, with Thread.currentThread().getContextClassLoader().getResourceAsStream("/hard/file/path/in/jar/file") within the Groovy Script, I can read the file, but with ClassLoader.getSystemClassLoader().getResourceAsStream("/hard/file/path/in/jar/file") , I can't. 为了证明这一点,使用Groovy脚本中的Thread.currentThread().getContextClassLoader().getResourceAsStream("/hard/file/path/in/jar/file") ,我可以读取文件,但可以使用ClassLoader.getSystemClassLoader().getResourceAsStream("/hard/file/path/in/jar/file") ,我不能。

So, does anyone know how to load the class in System ClassLoader from a Groovy Script without beginning to try some dirty hacks (like metaclassing getSystemClassloader to return the context classloader)? 因此,有谁知道如何从Groovy脚本中加载System ClassLoader中的类而又不尝试尝试一些肮脏的技巧(例如,通过元类化getSystemClassloader返回上下文类加载器)?

You could try adding the jar to the system classloader as well when your script runs, like so: 您也可以在脚本运行时尝试将jar添加到系统类加载器中,如下所示:

ClassLoader.systemClassLoader.addURL new File( '/path/to/jar/file' ).toURI().toURL()

PS: I assume you mean ClassLoader.getSystemClassLoader() in your question, rather than System.getSystemClassLoader() PS:我假设您的意思是ClassLoader.getSystemClassLoader() ,而不是System.getSystemClassLoader()

您可以尝试将jar放入%GROOVY_HOME%\\lib文件夹中,或者在groovy命令周围进行包装,并在开始Groovy进程之前修改%CLASSPATH%变量。

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

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