Groovy-在对象实例化期间忽略地图中的额外属性 [英] Groovy - Ignore extra attributes in a map during object instantiation

查看:106
本文介绍了Groovy-在对象实例化期间忽略地图中的额外属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使Groovy在对象实例化时忽略地图中的其他属性?示例:

Is there a way to make groovy ignore extra attributes in a map during object instantiation? Example:

class Banana{
    String name
}
def params = [name:'someGuy', age:13]
new Banana(params)

在此示例中,groovy引发了No这样的属性:age异常(显然是因为Banana类中未定义age.不依靠手动将仅所需属性从映射映射到Banana类的构造函数,是有没有办法告诉香蕉忽略额外的属性?

In this example, groovy throws a No such property: age exception (obviously because age isn't defined in the Banana class. Without resorting to manually mapping only the desired attributes from the map to the constructor of the Banana class, is there a way to tell Banana to ignore the extra attributes?

我注意到Grails域类没有遭受此问题的困扰,我在这里希望得到相同的行为!

I noticed that Grails domain classes do not suffer from this problem, and I would like the same behavior here!

感谢您的帮助和建议!

推荐答案

不幸的是,在Groovy中没有内置的方法可以做到这一点. Grails通过为域对象生成自己的构造函数来做到这一点.一个简单的解决方法是使用这样的构造函数:

Unfortunately, there's no built in way to do this in groovy. Grails does it by generating its own constructors for domain objects. A simple workaround is to use a constructor like this:

Banana(Map map) {
    metaClass.setProperties(this, map.findAll { key, value -> this.hasProperty(key) })
}

这篇关于Groovy-在对象实例化期间忽略地图中的额外属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆