0

In the older (1.x.x) versions of Groovy you can add constructors using metaClass.constructor

Example.metaClass.constructor << { String arg0 -> new Example(arg0, "") }

Is there a way to register constructors using the new Groovy 2.0 extension modules?

This seems to work:

Define an extension class as normal for Groovy 2 and just add the constructors in a static initialiser

public class ExampleHelper {
    static {
        Example.metaClass.constructor << { String arg0 -> new Example(arg0, "") }
    }
}
Michael Rutherfurd
  • 13,815
  • 5
  • 29
  • 40

1 Answers1

0

Not that I know of...

You could add a static factory method to the Example class ie:

class ExampleExtensionStatic {
  public static Example newInstance( Example type, String arg0 ) {
    new Example( arg0, '' )
  }
}

Then (after adding a link to this class in the staticExtensionClasses field of the org.codehaus.groovy.runtime.ExtensionModule file), you could do:

Example.newInstance( 'arg0' )

This is something worth asking on the mailing list to see if constructors are worth adding to the Module Extension system.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Thanks Tim. I suspected as much but I was hoping for different. I'm trying to make a project I'm working on interoperable between Groovy 1.x and 2. Maybe I need to look at the "register your own" features but I don't see any documentation for that yet :-( – Michael Rutherfurd Jul 02 '12 at 01:36
  • This is all I've found: http://docs.codehaus.org/display/GROOVY/Creating+an+extension+module – tim_yates Jul 02 '12 at 07:12
  • Yep, that was what I found. I was hoping to avoid the "Advanced Modules" bit as it is just check out these classes... – Michael Rutherfurd Jul 02 '12 at 09:13
  • Ahhh yeah, I haven't dug in to the 'Advanced Modules' bit yet... I guess it might be possible to write your own Module and registry classes -- but as I said, I haven't looked into that at all :-( – tim_yates Jul 02 '12 at 09:23