Scope of Groovy's ExpandoMetaClass?
Posted
by
TicketMonster
on Stack Overflow
See other posts from Stack Overflow
or by TicketMonster
Published on 2013-11-06T19:32:07Z
Indexed on
2013/11/06
21:54 UTC
Read the original article
Hit count: 153
Groovy exposes an ExpandoMetaClass
that allows you to dynamically add instance and class methods/properties to a POJO. I would like to use it to add an instance method to one of my Java classes:
public class Fizz {
// ...etc.
}
Fizz fizz = new Fizz();
fizz.metaClass.doStuff = { String blah -> fizz.buzz(blah) }
This would be the equivalent to refactoring the Fizz
class to have:
public class Fizz {
// ctors, getters/setters, etc...
public void doStuff(String blah) {
buzz(blah);
}
}
My question:
Does this add doStuff(String blah)
to only this particular instance of Fizz
? Or do all instances of Fizz
now have a doStuff(String blah)
instance method?
If the former, how do I get all instances of Fizz
to have the doStuff
instance method? I know that if I made the Groovy:
fizz.metaClass.doStuff << { String blah -> fizz.buzz(blah) }
Then that would add a static class method to Fizz
, such as Fizz.doStuff(String blah)
, but that's not what I want. I just want all instances of Fizz
to now have an instance method called doStuff
. Ideas?
© Stack Overflow or respective owner