Groovy web console

subscribe to the feed Subscribe
to this
site
https://stackoverflow.com/questions/50745518/overwrite-a-metaclass-property-in-groovy# (via #groovywebconsole)
tweet this snippet Tweet
this
script

https://stackoverflow.com/questions/50745518/overwrite-a-metaclass-property-in-groovy#

Published 4 months ago by Anonymous with tags stackoverflow
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
class Bike {}
class Bell { def ring() { println("calling " + this) } }  

def createNamespaces = {     return [ "bell": new Bell() ] }  
def resetNamespaces = { bike ->     
  bike.metaClass = null     
  createNamespaces().each { name, namespace ->       
        println("setting " + namespace)      
        bike.metaClass."$name" = namespace     
  } 
}  
 
def bike= new Bike() 
resetNamespaces(bike)
bike.bell.ring()

resetNamespaces(bike)
bike.bell.ring()