如何在脚本的多个文件中使用多个类? [英] How to use multiple classes in multiple files in scripts?

查看:67
本文介绍了如何在脚本的多个文件中使用多个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个不需要编译且无需安装Groovy即可运行的独立Groovy脚本.它运行良好,但无法识别除主脚本之外的任何其他脚本.

I need to make a standalone Groovy script that does not require compilation and runs without Groovy installed. It works well, but it fails to recognize any other script than the main script.

我的文件夹结构如下:

libs\
    groovy-all-2.4.3.jar
    ivy-2.4.0.jar
src\
    makeRelease.groovy
    ReleaseHelper.groovy

我正在从src文件夹中以这种方式启动脚本:

I am launching the script this way from the src folder:

java -cp"../libs/*" makeRelease.groovy

makeRelease看起来像这样:

makeRelease looks like this:

public class makeRelease {
    public static void main(String... args) {
         new ReleaseHelper()
         ...
    }
}

运行时,这是输出:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
src\makeRelease.groovy: 5: unable to resolve class ReleaseHelper

如何在此类可移植脚本中包含其他类(位于单独的文件中)?

How can I include other classes (that reside in separate files) in such portable scripts?

推荐答案

我认为这比您想象的要容易:

I think that it is easier than you think:

libs\
    groovy-all-2.4.3.jar
src\
    main.groovy
    Greeter.groovy

main.groovy

public class Main {
    public static void main(args) {
        println 'Main script starting...'
        def greeter = new Greeter()
        greeter.sayHello()
    }
}

Greeter.groovy

class Greeter {
    def sayHello() {
        println 'Hello!'
    }
}

只需将类包含在单独文件中的文件夹添加到类路径:

Simply add to the classpath the folders where you have the classes in separate files:

java -cp .;..\libs\groovy-all-2.4.3.jar groovy.ui.GroovyMain main.groovy

上面的结果:

Main script starting...
Hello!

这篇关于如何在脚本的多个文件中使用多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆