本文介绍了Metaclass deligate不是实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码添加动态属性。我使用MongoDB并且想要动态添加属性。这是我在单元测试时试图做的。

I have this stub of code to add dynamic attributes. I work with mongodb and i want to add the properties dynamically. This is what i tried to do when unit testing.

User.metaClass.dynamicAttributes = [:]

User.metaClass.propertyMissing = { String name ->
    delegate.dynamicAttributes[name]
}

User.metaClass.propertyMissing = { String name, value ->
    delegate.dynamicAttributes[name] = value
}

我超过了我的耐心限制!

But this fails and i am stepping over my patience limit!

User u = new User()
u.ppt = 0

User u2 = new User()
u2.ppt = 1

assert u2.ppt == 1
assert u.ppt == 0 // fails here, println shows that u.ppt is also 1!


推荐答案

更改此项

User.metaClass.dynamicAttributes = [:]

User.metaClass.propertyMissing = { String name ->
    delegate.dynamicAttributes[name]
}

User.metaClass.propertyMissing = { String name, value ->
    delegate.dynamicAttributes[name] = value
}

p>

to this

User.metaClass.propertyMissing = { String name ->
    if (!delegate.metaClass.hasProperty('dynamicAttributes') delegate.metaClass.dynamicAttributes = [:]
    delegate.dynamicAttributes[name]
}

User.metaClass.propertyMissing = { String name, value ->
    if (!delegate.metaClass.hasProperty('dynamicAttributes') delegate.metaClass.dynamicAttributes = [:]
    delegate.dynamicAttributes[name] = value
}

解决了它!我不确定,但它看起来像groovy共享通过metaClass提供的属性!

Solved it! I am not sure, but it seems like groovy shares the attribute put through metaClass!

这篇关于Metaclass deligate不是实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 03:56