每个对象的Groovy动态属性 [英] Groovy dynamic property per object
问题描述
使用Groovy 1.8。我正在尝试创建一个动态类定义,它将缓存每个对象的属性。我没有使用 propertyMissing
而不添加对象的属性就好了。我只是想缓存属性会更有效率。
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.
以下代码正常工作: / p>
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
将输出:
a C property
groovy.lang.MissingPropertyException: No such property: prop for class: C
如果我需要这个问题:
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
对于 A
,我得到crea新的属性,但行 this.metaClass。$ name=Dyna prop $ name
失败与:没有这样的属性:p1对于第5行的课程
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
有什么问题?
推荐答案
此代码应该做你想要的:
This code should do what you want:
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
这篇关于每个对象的Groovy动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!