Is there a way to replace using the metaclass object, a method that is of a super class. Example:
class A {
def doIt(){
two()
println 'do it!'
}
protected two(){
println 'two'
}
}
class B extends A{
def doLast(){
doIt()
}
}
B b = new B();
b.doIt()
/*
* two
* doit!
*/
b.metaClass.two = {
println 'my new two!'
}
b.doIt();
/*
* my new two!
* do it!
*/
Since two
and doIt
are declared in the same class, groovy will skip the meta-object protocol for this call. You can override this behavior by marking the super class as GroovyInterceptable
, which forces all method calls to go through invokeMethod
. For example:
class A implements GroovyInterceptable {
def doIt(){
two()
println 'do it!'
}
protected two(){
println 'two'
}
}
class B extends A {
def doLast(){
doIt()
}
}
B b = new B()
b.doIt() // prints two
b.metaClass.two = {
println 'my new two!'
}
b.doIt() // prints my new two!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With