groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Sean LeBlanc <>
Subject Metaclass programming and Groovy (2.3.7) traits
Date Fri, 17 Jul 2015 17:23:59 GMT
I'm trying to figure out the recommended way to write unit tests for 
classes that have methods implemented as traits that need to be 
overwritten with metaclass programming.

What I've noticed is that using an instance of the class doesn't seem to 
work, nor does using the class itself. (Commented out below)

It seems that setting is on the trait itself does work, however, this 
must be done before the first time the implementing class is created, or 
else setting the metaClass to null on the implementing class is required 
(also commented out below)?

Is there a better way to do this?

trait T {
   def speak() {
      println "trait version"

class C implements T {

def c = new C()
//c.metaClass.speak = { -> println "meta" }
//C.metaClass.speak = { -> println "meta" }

//C.metaClass = null

T.metaClass.speak = { println "meta class version" }
def c2 = new C()

View raw message