How to use multiple classes in multiple files in scripts?

a 夏天 提交于 2021-01-27 11:45:26

问题


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.

My folder structure is the following:

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

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

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

makeRelease looks like this:

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

When run this is the output:

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?


回答1:


I think that it is easier than you think:

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

Where main.groovy

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

and 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

The above yields:

Main script starting...
Hello!


来源:https://stackoverflow.com/questions/30753874/how-to-use-multiple-classes-in-multiple-files-in-scripts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!