Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy metaclass replace superclass method

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!
 */
like image 548
rascio Avatar asked May 07 '12 14:05

rascio


1 Answers

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!
like image 122
ataylor Avatar answered Nov 18 '22 02:11

ataylor