Groovy dynamic property per object

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?

+5
source share
3 answers

, :

class A {
  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
  }
}

a = new A()
println a.p1
println a.p1

:

create new propery p1
created new propery p1
Dyna prop p1
Dyna prop p1
+8

HashMap?

class Foo {
    def storage = [:]
    def propertyMissing(String name, value) { storage[name] = value }
    def propertyMissing(String name) { storage[name] }
}
def f = new Foo()
f.foo = "bar"

: http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing

: , ... , .

+6

ExpandoMetaClass (. , , 1.6 ).

, Runtime mixins. .

, blogpost, . groovy ( ).

, , 1.6 ExpandoMetaClass:

() . , ExpandoMetaClass, initialize(). initialize() .

+1

All Articles