| Excerpt |
|---|
|
Adding or overriding constructors |
Adding constructors is a little different to adding a method with ExpandoMetaClass. Essentially you use a special "constructor" property and either use the << or = operator to assign a closure. The arguments to the closure are of course the constructor arguments
| Code Block |
|---|
class Book {
String title
}
Book.metaClass.constructor << { String title -> new Book(title:title) }
def b = new Book("The Stand")
|
Be careful when adding constructors however, as it is very easy to get into stack overflow troubles. For example this code which overrides the default constructor:
| Code Block |
|---|
class Book {
String title
}
Book.metaClass.constructor = { new Book() }
def b = new Book("The Stand")
|
The above would produce a StackOverflowError as it rescursively keeps calling the same constructor through Groovy's MetaClass system. You can get around this by writing helper code to instantiate an instance outside of Groovy. For example this uses Spring's BeanUtils class and does not cause a StackOverflow:
| Code Block |
|---|
class Book {
String title
}
Book.metaClass.constructor = { BeanUtils.instantiateClass(Book) }
def b = new Book("The Stand")
|