Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Groovy classes in one file when running as a script

Tags:

groovy

I have a project with multiple groovy files, and I have several "tiny" classes that I want to put in a single file.

Basically, here is what I want:

Foo.groovy:

class Foo
{
    Foo() { println "Foo" }
}

Bar.groovy:

class Bar
{
    Bar() { println "Bar" }
}

class Baz
{
    Baz() { println "Baz" }
}

script.groovy:

#!/groovy/current/bin/groovy

new Foo()
new Bar()
new Baz()

And then:

$ groovy ./script.groovy 
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/home/tmp/script.groovy: 5: unable to resolve class Baz 
 @ line 5, column 1.
   new Baz()
   ^

1 error

Any idea?

like image 440
Christophe Avatar asked May 01 '15 21:05

Christophe


People also ask

Can you have multiple classes in one Javascript?

You can have more than one class per Java source file.

Can a Groovy class extend a Java class?

Yes, you may intermix Java and Groovy sources in a project and have source dependencies in either direction, including "extends" and "implements".

How do I create a Groovy script?

Create a Groovy ScriptFrom the Tools Main menu select Groovy > New Script. This opens the Groovy editor. Enter the Groovy code.

Can I use Java classes in Groovy?

Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.


1 Answers

When Groovy is run as a script without compilation, then classes are resolved by matching names to a corresponding *.groovy source files, so only classes where the class name matches the source filename can be found.

This is known problem marked as Not a Bug.

As a workaround you can compile classes first with groovyc and then run using java:

groovyc *
java -cp '/some/path/groovy-2.4.3/lib/groovy-2.4.3.jar;.' script
Foo
Bar
Baz
like image 119
Michal Kordas Avatar answered Oct 13 '22 00:10

Michal Kordas