Using ExpandoMetaClass Static Methods can be added dynamically, how can i use this ExpandoMetaClass in Singleton object, with overloaded static function in it, let say the sample program need to be re written using ExpandoMetaClass whats needs to changed in the below program
@Singleton
class testA {
def static zMap = [:]
static def X() {
Y()
}
static def Y() {
}
static def X(def var) {
Y(var)
}
static def Y(def var) {
zMap.put(var)
}
}
One of the reasons to use a singleton is to avoid having static state and methods in a class. If you're using
@Singleton
, there's no reason to have static methods or fields. The way to use a singleton is like this:You can extend the singleton using ExpandoMetaClass like so:
If you really want a static method, you can do something like this:
Note that if you override the class metaClass, rather than the instance metaClass, it won't apply to the instance if the instance has already been created. To get around this use
@Singleton(lazy = true)
and override the metaClass before accessing the instance.