Using Groovy 1.8. I'm trying to create a dynamic class definition that will cache properties per object. I did use propertyMissing
without adding the property to the object just fine. I just think caching the properties would be more efficient. Right?
Note that each instance must have its 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 for class: C
If I need to this problematically:
class A {
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"
}
}
a = new A()
println a.p1
For A
, I get as far as "create new property", but the line this.metaClass."$name" = "Dyna prop $name"
fails with: No such property: p1 for class at line 5
Whats wrong?