Skip to end of metadata
Go to start of metadata

ExpandoMetaClass - Adding 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

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:

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:

  • No labels

1 Comment

  1. Can we also use the metaClass to add new constructors to Java (not Groovy) classes? Doesn't seem to be working for me.