| Author |
I need metaClass advice for Groovy
|
Marc Peabody
pie sneak
Sheriff
Joined: Feb 05, 2003
Posts: 4695
|
|
I need another method on String. I used metaClass to do this: However, in all of the code examples I've seen on metaClass this trick has always been inside a script. In my application, though, I'm not running scripts - I have Groovy classes. I suppose I could place this metaClass thing in the beginning of any method that needs to call it... but that sure doesn't feel right. I thought about moving it to some listener or bootstrapper class that loads when my container loads, but then I have to make sure it also gets called for my unit tests and that feels sloppy too. Should metaClass not be used like this in an application (and keep it only in scripts)? Should I revert to the old school Java way and make a String utility class? [ April 08, 2008: Message edited by: Marc Peabody ]
|
A good workman is known by his tools.
|
 |
Marc Peabody
pie sneak
Sheriff
Joined: Feb 05, 2003
Posts: 4695
|
|
|
*bump*
|
 |
Venkat Subramaniam
Author
Ranch Hand
Joined: Jan 28, 2008
Posts: 79
|
|
|
Can you have this code in a static initialization block of a prominent class in your application? If this prominent class is guaranteed to be loaded pretty early in your application execution, you don't have to worry about making explicit calls to this code...
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18641
|
|
Another approach is to use a category: [ April 08, 2008: Message edited by: Jim Yingst ]
|
"I'm not back." - Bill Harding, Twister
|
 |
Venkat Subramaniam
Author
Ranch Hand
Joined: Jan 28, 2008
Posts: 79
|
|
|
Good point. Be aware, however, that Categories are more expensive and also injected methods are visible only within the same thread.
|
 |
Marc Peabody
pie sneak
Sheriff
Joined: Feb 05, 2003
Posts: 4695
|
|
The static block sounds like a pretty good idea. Thanks for the concise for loop, Jim.
|
 |
 |
|
|
subject: I need metaClass advice for Groovy
|
|
|