导入 Java 库 groovy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32180388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:47:07  来源:igfitidea点击:

Import Java library groovy

javagroovy

提问by Mattes

i want to use a method defined in the apache.common.net library in my groovy-Script.

我想在我的 groovy 脚本中使用 apache.common.net 库中定义的方法。

I first downloaded and included it in my config:

我首先下载并将其包含在我的配置中:

            this.class.classLoader.rootLoader.addURL(new URL("file:///${currentDir}/lib/commons-net-3.3.jar"))

Afterwards i try to use it in my groovy-script like this (to make it clear: the import pimpim.* imports also the classLoader above):

之后,我尝试在我的 groovy 脚本中使用它,如下所示(为了清楚起见:import pimpim.* 还导入了上面的 classLoader):

    import pimpim.*

import org.apache.commons.net.ftp.*

def pm = PM.getInstance("test")


public class FileUploadDemo {
  public static void main(String[] args) {
    FTPClient client = new FTPClient();

I also tried several annotations for the "import" like

我还为“导入”尝试了几个注释,例如

import org.apache.commons.net.ftp.FTPClient

But i keep getting this error:

但我不断收到此错误:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Y:\pimconsole\scripts\ftp.gy: 11: unable to resolve class FTPClient
 @ line 11, column 15.
       FTPClient client = new FTPClient();

What did i miss? Sorry, i am still new to groovy :/

我错过了什么?抱歉,我对 groovy 还是个新手:/

采纳答案by tim_yates

So, you can add it to the classpath when you start up your script;

因此,您可以在启动脚本时将其添加到类路径中;

groovy -cp .;lib/commons-net-3.3.jar ftp.gy

Or, you can add a @Grabannotation to your script, and Groovy will download the dependency and add it to the classpath before running (but this can not work if your scripts are executed on a box with no access to maven);

或者,您可以@Grab在脚本中添加注释,Groovy 会在运行之前下载依赖项并将其添加到类路径中(但如果您的脚本在无法访问 maven 的机器上执行,则这将不起作用);

@Grab('commons-net:commons-net:3.3')
import org.apache.commons.net.ftp.*

...rest of your script...

Or the classpath hacking route you have above shouldwork if you try:

或者,如果您尝试,上面的类路径黑客路线应该可以工作:

this.getClass().classLoader.rootLoader.addURL(new File("lib/commons-net-3.3.jar").toURL())