Where to properly initialize Groovy metaclasses?
Asked Answered
P

1

5

In a Groovy application, if you want to initialize metaclasses, where is the best place to put those initializations? In Grails apps, I've used the Bootstrap.groovy file. Is there something similar for an arbitrary Groovy app?

Edit: To clarify, I'm looking for a non-intrusive way of doing this that will guarantee it gets called when running the main application as well as in unit tests of the associated code.

Parmesan answered 1/8, 2011 at 19:30 Comment(0)
G
8

There's nothing like Bootstrap.groovy for standard groovy applications, but that doesn't stop you doing the same thing in your app and having a class or method that is called once on startup where you can add the metaClass initialization


Added from comments below:

You can write a DelegatingMetaClass for each class you wish to decorate, and place it in the package groovy.runtime.metaclass.[YOURPACKAGE].[YOURCLASS]MetaClass

This page explains the steps required to do this (2nd item on the page)

Grisly answered 1/8, 2011 at 20:5 Comment(5)
Is there a non-intrusive way of doing this that will guarantee it gets called when running the main application as well as in unit tests of the associated code?Parmesan
@Alan You can write a DelegatingMetaClass for each class you wish to decorate, and place it in the package groovy.runtime.metaclass.[YOURPACKAGE].[YOURCLASS]MetaClass this page explains the steps required to do this (2nd item on the page)Grisly
@tim IMO, the comment above should be moved into the answer itselfEveevection
@tim thanks, I'd have done it myself, but I'm a little shy about editing the posts of users who are ahead of me in the Groovy league :) I've further hindered my goal of reclaiming my rightful spot by upvoting this answerEveevection
Does this method also work for ExpandoMetaClass initialization?Parmesan

© 2022 - 2024 — McMap. All rights reserved.