Using Groovy 1.8. I am trying to create a dynamic class definition that will cache properties for each object. I used propertyMissingwithout adding a property to the object just fine. I just think property caching will be more efficient. Correctly?
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 this is problematic:
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 AI get to "create new property", but the line this.metaClass."$name" = "Dyna prop $name"fails:No such property: p1 for class at line 5
What's wrong?
source
share