Groovy web console

subscribe to the feed Subscribe
to this

groovy metaclass

Published 3 months ago by lou with tags groovy metaclass
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
class C {def v,r={v=Math.random()}}

new C().with{ c-> // I'm a huge fan of "with"
  println("c with v:${c.v}") }

C.metaClass.r = {delegate.v=new Random().nextInt(100)}
new C().with{ c-> // did I say I like "with"
  println("better c with v:${c.v}") }

Object.metaClass.bestR = {delegate.v=new Random().nextInt(10**6)}
Object.metaClass.v = null
new C().with{ c->
  c.bestR() // we modified every Object that can exist on the fly
  println("better c with v:${c.v}") }
"foo".with{ s->
  println("better EVERYTHING with v:${s.v}") }

C.metaClass.methodMissing = {String n, args -> println "Who do you think you are, calling '${n}'"}
new C().i_dont_exist()