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

« Previous Version 6 Next »

GroovyBeans are JavaBeans but using a much simpler syntax.
Here's an example:

Notice how the properties look just like public fields. You can also set named properties in a bean constructor in Groovy. In Groovy, fields and properties have been merged so that they act and look the same. So, the Groovy code above is equivalent to the following Java code:

Property and field rules

When Groovy is compiled to bytecode, the following rules are used.

  • If the property is private, then a Java field is used to represent the property.
  • If a public or protected property is declared (properties are public by default), then a public or protected getter and setter are created along with a private Java field.
  • If you don't declare getters or setters for public or protected properties, they are automatically created for you at the bytecode level.
  • If you create a public or protected property, you can overload any auto-created methods.

So, for example, you could create a read only property or a public read-only property with a protected setter like this:

Note that properties need <i>some</i> kind of identifier: variable type ("String"), the "def" keyword, or the "@Property" annotation.

Closures and listeners

Though Groovy doesn't support anonymous inner classes, it is possible to define action listeners inline through the means of closures. So instead of writing in Java:

You can do that in Groovy with a closure:

This mechanism is heavily used in the Swing builder to define event listeners for various components and listeners. The JavaBeans introspector is used to make event listener methods available as properties which can be set with a closure:

The Java Beans introspector (java.beans.Introspector) which will look for a BeanInfo for your bean or create one using its own naming conventions. (See the Java Beans spec for details of the naming conventions it uses if you don't provide your own BeanInfo class). We're not performing any naming conventions ourselves - the standard Java Bean introspector does that for us.

Basically the BeanInfo is retrieved for a bean and its EventSetDescriptors are exposed as properties (assuming there is no clash with regular beans). It's actually the EventSetDescriptor.getListenerMethods() which is exposed as a writable property which can be assigned to a closure.

  • No labels