Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Classes are defined in Groovy similarly to Java. Methods can be class (static) or instance based
and can be public, protected, private and support all the usual Java modifiers like synchronized.

One difference with Groovy is that by default things are public unless you specify otherwise.

Groovy also merges the idea of fields and properties together to make code simpler, please refer
to the GroovyBeans section for details of how they work.

Each class in Groovy is a Java class at the bytecode / JVM level. Any methods declared will
be available to Java and vice versa. You can specify the types of parameters or return types
on methods so that they work nicely in normal Java code. Also you can implement interfaces
or overload Java methods using this approach.

If you omit the types of any methods or properties they will default to java.lang.Object at the
bytecode/JVM level.

h2 Scripts

Groovy supports plain scripts, which do not have a class declaration. Here's the hello world
script

Error rendering macro 'code': Invalid value specified for parameter 'lang'
println "Nice cheese Gromit!"

You can run scripts in the interactive terminal or inside your own Java code or via the Bean Scripting Framework.

If you compile the above script to bytecode using the groovyc Ant task you get
a single class named after the name of the script. e.g. if this was saved in Foo.script you'd get
a Foo.class file.

You can run this Java code on the command line (assuming you're classpath has groovy.jar and asm.jar).

This will execute the autogenerated main(String[] args) method in the bytecode which instantiates the Foo
class, which extends Script class
and then call its ~run()~ method.

If you like you could use this class directly in Java code, passing in variables to the script.

There's no need to use a Binding if you don't want to; Foo will have a no-argument constructor
as well. Though using a Binding you can easily pass in variables. After the end of the script any variables created will be in the Binding for you to access in Java.

h2 Scripts and functions

If you just want to write some simple scripts and need some simple functions you can declare functions without writing a class.
One difference from normal class-based groovy is that the ~def~ keyword is required to define a function outside of a class.

Here's an example of a simple script with a function. Note that if ever you need things like static or instance variables and so forth then maybe its time to actually write a class (smile)

Error rendering macro 'code': Invalid value specified for parameter 'lang'
def foo(list, value) {
    println "Calling function foo() with param ${value}"
    list << value
}

x = []
foo(x, 1)
foo(x, 2)
assert x == [1, 2]

println "Creating list ${x}"
  • No labels