Groovy metaclass replace superclass method

Is there a way to replace using a metaclass object, a super class method. 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! */ 
+4
source share
1 answer

Since two and doIt declared in the same class, groovy will skip the meta object protocol for this call. You can override this behavior by marking the superclass as GroovyInterceptable , which causes all method calls to go through invokeMethod . For instance:

 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! 
+7
source

Source: https://habr.com/ru/post/1411124/


All Articles