@Documented
@Retention(value=SOURCE)
@Target(value=FIELD)
public @interface Delegate
class Event {
@Delegate
Date when
String title, url
}
def gr8conf = new Event(title: "GR8 Conference",
url: "http://www.gr8conf.org",
when: Date.parse("yyyy/MM/dd", "2009/05/18"))
def javaOne = new Event(title: "JavaOne",
url: "http://java.sun.com/javaone/",
when: Date.parse("yyyy/MM/dd", "2009/06/02"))
assert gr8conf.before(javaOne.when)
In this example, the Event
class will have a method called
before(Date otherDate)
as well as other public methods of the
Date
class.
The implementation of the before()
method will look like this:
public boolean before(Date otherDate) { return when.before(otherDate); }By default, the owner class will also be modified to implement any interfaces implemented by the field. So, in the example above, because
Date
implements Cloneable
the following will be true:
assert gr8conf instanceof CloneableThis behavior can be disabled by setting the annotation's
interfaces
element to false,
i.e. @Delegate(interfaces = false)
, e.g. in the above
example, the delegate definition would become:
@Delegate
(interfaces = false) Date when
and the following would be true:
assert !(gr8conf instanceof Cloneable)If multiple delegate fields are used and the same method signature occurs in more than one of the respective field types, then the delegate will be made to the first defined field having that signature. If this does occur, it might be regarded as a smell (or at least poor style) and it might be clearer to do the delegation by long hand. By default, methods of the delegate type marked as
@Deprecated
are
not automatically added to the owner class. You can force these methods to
be added by setting the annotation's deprecated
element to true,
i.e. @Delegate(deprecated = true)
.
For example, in the example above if we change the delegate definition to:
@Delegate
(deprecated = true) Date when
then the following additional lines will execute successfully (during 2009):
assert gr8conf.year + 1900 == 2009 assert gr8conf.toGMTString().contains(" 2009 ")Otherwise these lines produce a groovy.lang.MissingPropertyException or groovy.lang.MissingMethodException respectively as those two methods are
@Deprecated
in Date
.
Technical notes:
GroovyObject
interface
are not candidates for delegation
@Delegate
field
@Delegate
field
@Delegate
with default method arguments is known not to work in some cases. We recommend
not using these features together.
Modifier and Type | Optional Element and Description |
---|---|
boolean |
deprecated |
boolean |
interfaces |