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?
You can have more than one class per Java source file.
Yes, you may intermix Java and Groovy sources in a project and have source dependencies in either direction, including "extends" and "implements".
Create a Groovy ScriptFrom the Tools Main menu select Groovy > New Script. This opens the Groovy editor. Enter the Groovy code.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With