grails - Grails在对象引用上设置元类属性

标签 grails groovy metaclass

使用Grails域对象,我偶然发现了尝试设置某些属性的问题。

var stepchild=parent.children.find{ it.id==xInt };
stepchild.metaClass.birthMom=biologicalMothersName;

parent.children.each{child->
    //when it gets to stepchild no metaclass property birthMom exists....
}

同样,不会在引用的对象上设置自定义错误
var stepchild=parent.children.find{ it.id==xInt };
stepchild.errors.rejectValue('parent',"Not biological parent");

parent.children.each{child->
    //when it gets to stepchild no errors....
}

我猜find {}没有返回对父级子项的真实引用?

最佳答案

对于尝试在stepChild对象上设置属性/属性的方式,应使用MetaClass.setAttribute()方法:

stepchild.metaClass.setAttribute(stepChild,'birthMom', biologicalMothersName)

关于grails - Grails在对象引用上设置元类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678960/

相关文章:

grails - 域类的单元测试用例(测试约束)-Grails

git - 在 Jenkins 上进行 git 时检查特定文件夹

python - 如何包装类的每个方法?

ruby - 在打开的单例类中调用单例类方法

interface - Groovy:为接口(interface)委托(delegate)元类?

grails - 如何在Grails中将 Controller 设置为以纯文本形式响应

http - 在 grails 中编写代理

grails - Netbeans Groovy 1.8支持

grails - grails run-app返回 “context initialization failed”的奇怪情况

java - Groovy 中的 IDE,这可能吗?