Groovy dynamic property per object -
using groovy 1.8. i'm trying create dynamic class definition cache properties per object. did use propertymissing without adding property object fine. think caching properties more efficient. right?
note each instance must have own different properties.
the code below works fine:
class c {} def c = new c() c.metaclass.prop = "a c property" println c.prop def x = new c() x.prop will output:
a c property groovy.lang.missingpropertyexception: no such property: prop class: c if need problematically:
class { def propertymissing(string name) { if(!this.hasproperty(name)) { println "create new propery $name" this.metaclass."$name" = "dyna prop $name" println "created new propery $name" } this.metaclass."$name" } } = new a() println a.p1 for a, far "create new property", line this.metaclass."$name" = "dyna prop $name" fails with: no such property: p1 class @ line 5
whats wrong?
this code should want:
class { a() { def mc = new expandometaclass( a, false, true) mc.initialize() this.metaclass = mc } def propertymissing( string name ) { println "create new propery $name" def result = "dyna prop $name" this.metaclass."$name" = result println "created new propery $name" result } } = new a() println a.p1 println a.p1 that outputs:
create new propery p1 created new propery p1 dyna prop p1 dyna prop p1
Comments
Post a Comment